简体   繁体   English

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

[英]Using the amount of bars to set the width/labelsize of a bar chart

I am pretty new to using Matplotlib 我是使用Matplotlib的新手

I couldn't figure out how to apply the things I found to my own graph, so I decided to make my own post 我不知道如何将发现的内容应用于自己的图表,所以我决定发表自己的文章

I use this code to generate my bar chart: 我使用以下代码生成条形图:

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()

But I don't understand how to change the size of the plot? 但我不知道如何更改地块的大小? because when I use plt.figure(figsize=(p1,p2)) 因为当我使用plt.figure(figsize=(p1,p2))

I get an empty plot with the correct labels ( But it does apply the size to the piechart i create later? ) And the barchart i originally wanted to create has basic 1-8 labels. 我得到一个带有正确标签的空图(但是它是否将大小应用于以后创建的饼图?)而我最初想要创建的条形图具有基本的1-8标签。

I want to change the size based on the amount of bars are created because sometimes the data I use doesn't contain one of the categories. 我想根据创建的条形数量更改大小,因为有时我使用的数据不包含类别之一。

With as few changes as humanly possible to your current code, the way to do this is to add the following line right after you define p1 and p2 : 在对当前代码进行尽可能少的人为更改的情况下,执行此操作的方法是在定义p1p2之后立即添加以下行:

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

The above will set the size of the current Figure object that pyplot is using to make plots. 上面将设置pyplot用于绘制图形的当前Figure对象的大小。 In the future, you may way to switch over to using the Axes -based interface to Matplotlib , as it's much more powerful and flexible in general: 将来,您可能会切换到对Matplotlib使用基于Axes的界面 ,因为它通常更强大,更灵活:

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)) is the correct approach. plt.figure(figsize=(p1,p2))是正确的方法。 The question is hence a bit unclear, because you just need to put it in your code, eg 因此,这个问题还不清楚,因为您只需要将其放入代码中即可,例如

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

# ...

plt.bar(...)

This is also shown in the question: How do you change the size of figures drawn with matplotlib? 问题中也显示了这一点: 如何更改用matplotlib绘制的图形的大小?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM