[英]Force bins with zero-height in matplotlib bar plot
Consider the following script: 请考虑以下脚本:
import pylab
counts = [0,0,0,125,56,0,0,0,34,77,123,0,0,0]
pylab.bar(*zip(*enumerate(counts)), align='center')
pylab.show()
When I run this I get the following image. 当我运行这个时,我得到以下图像。
As you can see the 0-height bins at the edges of the plot are not plotted. 如您所见,未绘制绘图边缘的0高度分档。 However, I want them indeed to be plotted.
但是,我确实希望它们能够被绘制出来。 What can I do to achieve this?
我能做些什么来实现这个目标?
I know that I can set the x_lim of the axes ( Axes.set_xlim
). 我知道我可以设置轴的x_lim(
Axes.set_xlim
)。 If no other option exists, what approach takes most elegantly into account the width of the bars? 如果不存在其他选项,那么哪种方法最优雅地考虑了条的宽度?
One way would be something similar to the following: 一种方式类似于以下内容:
import pylab
counts = [0,0,0,125,56,0,0,0,34,77,123,0,0,0]
artists = pylab.bar(*zip(*enumerate(counts)), align='center')
lefts = [item.get_x() for item in artists]
rights = [item.get_x() + item.get_width() for item in artists]
pylab.xlim([min(lefts), max(rights)])
pylab.show()
Found another solution that may be working more reliably than set_xlim
: 找到另一个可能比
set_xlim
更可靠的解决方案:
import pylab
counts = [0,0,0,125,56,0,0,0,34,77,123,0,0,0]
# add a epsilon to counts to force bins to be plotted
epsilon = 1e-7
counts = [x+epsilon for x in counts]
pylab.bar(*zip(*enumerate(counts)), align='center')
pylab.show()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.