首页 > 解决方案 > 使用条形图的数量来设置条形图的宽度/标签大小

问题描述

我对使用 Matplotlib 很陌生

我不知道如何将我发现的东西应用到我自己的图表中,所以我决定自己发帖

我使用此代码生成我的条形图:

p = (len(dfrapport.index))

p1 = p * 2.5
p2 = p * 1.5

height = dfrapport['aantal']
bars = dfrapport['soort']
y_pos = np.arange(len(bars))


plt.bar(y_pos, height, color = ['black', 'red','orange', 'yellow', 'green', 'blue', 'cyan'])

plt.title('Aantal noodstoppen per categorie')
plt.xlabel('categorieën')
plt.ylabel('aantal')
plt.tick_params(axis='x', which='major', labelsize=p2)

plt.xticks(y_pos, bars)
plt.show()

但我不明白如何改变情节的大小?因为当我使用plt.figure(figsize=(p1,p2))

我得到一个带有正确标签的空图(但它确实将大小应用于我稍后创建的饼图?)并且我最初想要创建的条形图具有基本的 1-8 个标签。

我想根据创建的条形数量更改大小,因为有时我使用的数据不包含其中一个类别。

标签: pythonpandasmatplotlib

解决方案


对当前代码进行尽可能少的更改,方法是在定义p1and之后添加以下行p2

plt.gcf().set_size_inches(p1,p2)

以上将设置用于制作绘图的当前Figure对象的大小。pyplot将来,您可能会切换到使用Axes基于 - 的 Matplotlib 接口,因为它通常更加强大和灵活:

p = (len(dfrapport.index))

p1 = p * 2.5
p2 = p * 1.5

height = dfrapport['aantal']
bars = dfrapport['soort']
y_pos = np.arange(len(bars))

fig = plt.figure(figsize=(p1,p2))
ax = fig.gca()
ax.bar(y_pos, height, color = ['black', 'red','orange', 'yellow', 'green', 'blue', 'cyan'])

ax.set_title('Aantal noodstoppen per categorie')
ax.set_xlabel('categorieën')
ax.set_ylabel('aantal')
ax.xaxis.set_tick_params(which='major', labelsize=p2)

ax.set_xticks(y_pos, bars)
fig.show()

推荐阅读