使用每月数据控制 matplotlib 中的条形宽度 [英] Controlling bars width in matplotlib with per-month data

查看:32
本文介绍了使用每月数据控制 matplotlib 中的条形宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我用条形图绘制每月采样的数据时,它们的宽度非常薄.如果我将 X 轴次要定位器设置为 DayLocator(),我可以看到条形宽度调整为 1 天,但我希望它们填满一个月.

When I plot data sampled per month with bars, their width is very thin. If I set X axis minor locator to DayLocator(), I can see the bars width is adjusted to 1 day, but I would like them to fill a whole month.

我尝试将次要刻度定位器设置为 MonthLocator() 没有效果.

I tried to set the minor ticks locator to MonthLocator() without effect.

也许一个例子会更明确,这里是一个 ipython -pylab 我的意思的例子:

Maybe an example will be more explicit, here is an ipython -pylab example of what I mean :

x = [datetime.datetime(2008, 1, 1, 0, 0),
    datetime.datetime(2008, 2, 1, 0, 0),
    datetime.datetime(2008, 3, 1, 0, 0),
    datetime.datetime(2008, 4, 1, 0, 0),
    datetime.datetime(2008, 5, 1, 0, 0),
    datetime.datetime(2008, 6, 1, 0, 0),
    datetime.datetime(2008, 7, 1, 0, 0),
    datetime.datetime(2008, 8, 1, 0, 0),
    datetime.datetime(2008, 9, 1, 0, 0),
    datetime.datetime(2008, 10, 1, 0, 0),
    datetime.datetime(2008, 11, 1, 0, 0),
    datetime.datetime(2008, 12, 1, 0, 0)]

y = cos(numpy.arange(12) * 2)

bar(x, y)

这提供了 12 个 2 像素宽的条,我希望它们更宽并逐月延长.

This gives 12 2 pixels wide bars, I would like them to be wider and extend from month to month.

推荐答案

只需使用 width 关键字参数:

bar(x, y, width=30)

或者,因为不同的月份有不同的天数,为了让它看起来更好,你可以使用一个序列:

Or, since different months have different numbers of days, to make it look good you can use a sequence:

bar(x, y, width=[(x[j+1]-x[j]).days for j in range(len(x)-1)] + [30])

这篇关于使用每月数据控制 matplotlib 中的条形宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆