关于python:Matplotlib直方图标签文本拥挤

Matplotlib histogram label text crowded

我在matplotlib中制作直方图,每个bin的文本标签彼此重叠,如下所示:
enter image description here

我尝试按照另一种解决方案旋转x轴上的标签

1
2
3
cuisine_hist = plt.hist(train.cuisine, bins=100)
cuisine_hist.set_xticklabels(rotation=45)
plt.show()

但是我收到错误消息'tuple' object has no attribute 'set_xticklabels'。 为什么? 我该如何解决这个问题? 或者,如何"转置"绘图,使标签位于垂直轴上?


plt.hist的返回值不是用于运行函数set_xticklabels的返回值:

运行该功能的是matplotlib.axes._subplots.AxesSubplot,您可以从此处获得:

1
2
3
4
fig, ax = plt.subplots(1, 1)
cuisine_hist = ax.hist(train.cuisine, bins=100)
ax.set_xticklabels(rotation=45)
plt.show()

从plt.hist的"帮助"中:

1
2
3
4
5
6
7
8
9
10
Returns
-------
n : array or list of arrays
    The values of the histogram bins. See *normed* or *density*

bins : array
    The edges of the bins. ...

patches : list or list of lists
   ...


这可能有用,因为它与旋转标签有关。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import matplotlib.pyplot as plt


x = [1, 2, 3, 4]
y = [1, 4, 9, 6]
labels = ['Frogs', 'Hogs', 'Bogs', 'Slogs']

plt.plot(x, y, 'ro')
# You can specify a rotation for the tick labels in degrees or with keywords.
plt.xticks(x, labels, rotation='vertical')
# Pad margins so that markers don't get clipped by the axes
plt.margins(0.2)
# Tweak spacing to prevent clipping of tick-labels
plt.subplots_adjust(bottom=0.15)
plt.show()

所以我认为

1
plt.xticks(x, labels, rotation='vertical')

在这里很重要。


干得好。 我将两个答案集中在一个示例中:

1
2
3
4
5
6
7
8
9
10
# create figure and ax objects, it is a good practice to always start with this
fig, ax = plt.subplots()

# then plot histogram using axis
# note that you can change orientation using keyword
ax.hist(np.random.rand(100), bins=10, orientation="horizontal")

# get_xticklabels() actually gets you an iterable, so you need to rotate each label
for tick in ax.get_xticklabels():
    tick.set_rotation(45)

它产生带有旋转的X线和水平直方图的图形。
enter image description here