首页 > 解决方案 > Matplotlib 直方图标签文本拥挤

问题描述

我在 matplotlib 中制作直方图,每个 bin 的文本标签相互重叠,如下所示: 在此处输入图像描述

我尝试通过遵循另一个解决方案来旋转 x 轴上的标签

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

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

标签: pythonmatplotlibhistogram

解决方案


干得好。我在一个例子中将这两个答案混为一谈:

# 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 刻度和水平直方图的图形。 在此处输入图像描述


推荐阅读