Python 使用 matplotlib 中的 dataframe.plot() 函数编辑条的宽度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14824456/
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
Edit the width of bars using dataframe.plot() function in matplotlib
提问by Osmond Bishop
I am making a stacked bar plot using:
我正在使用以下方法制作堆积条形图:
DataFrame.plot(kind='bar',stacked=True)
I want to control width of bars so that the bars are connected to each other like a histogram.
我想控制条的宽度,以便条像直方图一样相互连接。
I've looked through the documentation but to no avail - any suggestions? Is it possible to do it this way?
我已经查看了文档但无济于事 - 有什么建议吗?可以这样做吗?
采纳答案by Murkbeard
For anyone coming across this question:
对于遇到这个问题的任何人:
Since pandas 0.14, plotting with bars has a 'width' command: https://github.com/pydata/pandas/pull/6644
从熊猫 0.14 开始,用条形图绘制有一个“宽度”命令:https: //github.com/pydata/pandas/pull/6644
The example above can now be solved simply by using
上面的例子现在可以简单地通过使用来解决
df.plot(kind='bar', stacked=True, width=1)
回答by bmu
If think you have to "postprocess" the barplot with matplotlib as pandas internally sets the width of the bars.
如果认为您必须使用 matplotlib 对条形图进行“后处理”,因为 Pandas 会在内部设置条形图的宽度。
The rectangles which form the bars are in container objects. So you have to iterate through these containers and set the width of the rectangles individually:
形成条形的矩形位于容器对象中。所以你必须遍历这些容器并单独设置矩形的宽度:
In [208]: df = pd.DataFrame(np.random.random((6, 5)) * 10,
index=list('abcdef'), columns=list('ABCDE'))
In [209]: df
Out[209]:
A B C D E
a 4.2 6.7 1.0 7.1 1.4
b 1.3 9.5 5.1 7.3 5.6
c 8.9 5.0 5.0 6.7 3.8
d 5.5 0.5 2.4 8.4 6.4
e 0.3 1.4 4.8 1.7 9.3
f 3.3 0.2 6.9 8.0 6.1
In [210]: ax = df.plot(kind='bar', stacked=True, align='center')
In [211]: for container in ax.containers:
plt.setp(container, width=1)
.....:
In [212]: x0, x1 = ax.get_xlim()
In [213]: ax.set_xlim(x0 -0.5, x1 + 0.25)
Out[213]: (-0.5, 6.5)
In [214]: plt.tight_layout()



