Skip to main content
 首页 » 编程设计

python之Matplotlib 直方图标签文本拥挤

2024年12月31日9jillzhang

我在 matplotlib 中制作直方图,每个 bin 的文本标签像这样相互重叠:

我尝试按照 another solution 旋转 x 轴上的标签

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

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

请您参考如下方法:

给你。我将这两个答案集中在一个例子中:

# 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 刻度和水平直方图的图形。