Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Controlling bars width in matplotlib with per-month data

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.

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

[edit]

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)

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

like image 236
Luper Rouch Avatar asked May 20 '09 08:05

Luper Rouch


People also ask

How do I reduce the width of a bar in MatPlotLib?

To set width for bars in a Bar Plot using Matplotlib PyPlot API, call matplotlib. pyplot. bar() function, and pass required width value to width parameter of bar() function. The default value for width parameter is 0.8.

How will you change the width of the bars in a bar graph?

If graphs have different number of bars, Prism will change the width of the bars to fill in the specified width (length) of the X axis. The fewer bars you have, the wider they become to fit the range of the X axes length. The more bars you have, the shorter the width.

How do I increase the space between bars in MatPlotLib?

MatPlotLib with Python To change the space between bars when drawing multiple barplots in Pandas within a group, we can use linewidth in plot() method.


1 Answers

Just use the width keyword argument:

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])
like image 172
Jouni K. Seppänen Avatar answered Sep 27 '22 20:09

Jouni K. Seppänen