Python Matplotlib:如何更改双条形图的 figsize

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51080491/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 19:43:09  来源:igfitidea点击:

Matplotlib: How to change figsize for double bar plot

pythonmatplotlib

提问by Utkarsh Ranjan

I have plotted a double bar plot in matplotlib using the following code:

我使用以下代码在 matplotlib 中绘制了一个双条形图:

x = pd.Series(range(12))
y = self.cust_data['Cluster_ID'].value_counts().sort_index()
z = self.cust_data['Cluster_ID_NEW'].value_counts().sort_index()
plt.bar(x + 0.0, y, color = 'b', width = 0.5)
plt.bar(x + 0.5, z, color = 'g', width = 0.5)
plt.legend(['Old Cluster', 'New Cluster'])
plt.savefig("C:\Users\utkarsh.a.ranjan\Documents\pyqt_data\generate_results\bar", bbox_inches='tight',pad_inches=0.1)
plt.clf()

I want to use the figsize parameter to make the resultant plot bigger in size. This is easy when plotting a single bar plot, but here I am confused as to where to put the figsize parameter.

我想使用 figsize 参数使结果图的尺寸更大。绘制单个条形图时这很容易,但在这里我对 figsize 参数的放置位置感到困惑。

回答by nahusznaj

You could set the size with figsize

你可以设置大小 figsize

import matplotlib.pyplot as plt

f, ax = plt.subplots(figsize=(18,5)) # set the size that you'd like (width, height)
plt.bar([1,2,3,4], [0.1,0.2,0.3,0.4], label = 'first bar')
plt.bar([10,11,12,13], [0.4,0.3,0.2,0.1], label = 'second bar')
ax.legend(fontsize = 14)

enter image description here

在此处输入图片说明

回答by westr

The best way to do that follows a more OO approach:

最好的方法是遵循更面向对象的方法:

fig, ax = plt.subplots(figsize=(12,12))
ax.bar(x + 0.0, y, color = 'b', width = 0.5)
ax.bar(x + 0.5, z, color = 'g', width = 0.5)
ax.legend(['Old Cluster', 'New Cluster'])
fig.savefig("C:\Users\utkarsh.a.ranjan\Documents\pyqt_data\generate_results\bar", bbox_inches='tight',pad_inches=0.1)
plt.clf()

You also might want to add format to your filename. If not, the format is taken from your rc parameter savefig.format, which is usually png.

您可能还想为文件名添加格式。如果不是,则格式取自您的 rc 参数savefig.format,通常是png.

BTW, if you want to stick to your code as much as possible, you can also add the line before your plt.bar(...):

顺便说一句,如果你想尽可能地坚持你的代码,你也可以在你的之前添加一行plt.bar(...)

plt.figure(figsize=(12,12))