我正在matplotlib中制作直方图,每个bin的文本标签相互重叠,如下所示:
我尝试按照another solution
沿x轴旋转标签GetEnvironmentVariable
但是我收到错误消息cuisine_hist = plt.hist(train.cuisine, bins=100)
cuisine_hist.set_xticklabels(rotation=45)
plt.show()
。为什么?我该如何解决这个问题?或者,如何“转置”绘图,使标签位于垂直轴上?
答案 0 :(得分:1)
plt.hist
的返回值不是您用来运行函数set_xticklabels
的返回值:
正在运行该功能的是matplotlib.axes._subplots.AxesSubplot
,您可以从此处获取:
fig, ax = plt.subplots(1, 1)
cuisine_hist = ax.hist(train.cuisine, bins=100)
ax.set_xticklabels(rotation=45)
plt.show()
从plt.hist的“帮助”中:
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 :(得分:0)
您在这里。我将两个答案集中在一个示例中:
# 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)
答案 2 :(得分:0)
This可能会有所帮助,因为它与旋转标签有关。
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()
所以我认为
plt.xticks(x, labels, rotation='vertical')
在这里很重要。