使用条形图的数量来设置条形图的宽度/标签大小



我对使用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))

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

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

在对当前代码进行尽可能少的更改的情况下,执行此操作的方法是在定义p1p2之后立即添加以下行:

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

以上内容将设置pyplot用于绘制的当前Figure对象的大小。在未来,您可以切换到使用基于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()

plt.figure(figsize=(p1,p2))是正确的方法。因此,这个问题有点不清楚,因为你只需要把它放在你的代码中,例如

p = (len(dfrapport.index))
p1 = p * 2.5
p2 = p * 1.5
plt.figure(figsize=(p1,p2))
# ...
plt.bar(...)

这也体现在问题中:如何更改使用matplotlib绘制的图形的大小?

最新更新