[英]How to remove gaps between bars in Matplotlib bar chart
I'm making a bar chart in Matplotlib with a call like this:我正在 Matplotlib 中制作条形图,调用如下:
xs.bar(bar_lefts, bar_heights, facecolor='black', edgecolor='black')
I get a barchart that looks like this:我得到一个看起来像这样的条形图:
What I'd like is one with no white gap between consecutive bars, eg more like this:我想要的是连续条之间没有白色间隙的,例如更像这样:
Is there a way to achieve this in Matplotlib using the bar()
function?有没有办法使用bar()
function 在 Matplotlib 中实现这一点?
Add width=1.0
as a keyword argument to bar()
.将width=1.0
作为关键字参数添加到bar()
。 Eg例如
xs.bar(bar_lefts, bar_heights, width=1.0, facecolor='black', edgecolor='black')
. xs.bar(bar_lefts, bar_heights, width=1.0, facecolor='black', edgecolor='black')
。
This will fill the bars gaps vertically.这将垂直填充条形间隙。
Just set the width 1 over the number of bars, so:只需在条形数量上设置宽度 1,因此:
width = 1 / len(bar_lefts)
xs.bar(bar_lefts, bar_heights, width=width, color='black')
It has been 8 years since this question was asked, and the matplotlib API now has built-in ways to produce filled, gapless bars: pyplot.step()
and pyplot.stairs()
with the argument fill=True
.自从提出这个问题以来已经 8 年了,matplotlib API 现在有内置的方法来生成填充的、无间隙的条形: pyplot.step()
和pyplot.stairs()
,参数为fill=True
。
See the docs for a fuller comparison, but the primary difference is that step()
defines the step positions with N x
and N y
values just like plot()
would, while stairs()
defines the step positions with N heights and N+1 edges, like what hist()
returns.请参阅文档以获得更完整的比较,但主要区别在于step()
定义了 N x
和 N y
值的步骤位置,就像plot()
一样,而stairs()
定义了 N 个高度和 N+1 的步骤位置边缘,就像hist()
返回的那样。 It is a subtle difference, and I think both tools can create the same outputs.这是一个微妙的区别,我认为这两种工具都可以创建相同的输出。
You can set the width equal to the distance between two bars:您可以将宽度设置为等于两个条之间的距离:
width = bar_lefts[-1] - bar_lefts[-2]
xs.bar(bar_lefts, bar_heights, width=width)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.