Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to plot a rectangle behind a function over time

I'm plotting a timeseries in pandas using matplotlib and I'm trying to color a plot look like this.

Illustration on the wanted result

I have the times for the A-F points. I've tried to get the position of them in the plot using

gcf().canvas.mpl_connect('button_press_event', debug_print_onclick_event)

and ended up with x positions being around 22'395'850 (not even close to unixtime :S)

My code basically looks like this:

plot = data.plot(legend=False) #where data is the timeseries (pandas.DataFrame).
plot.add_patch(
    plt.Rectangle(
        (0,22395760), 
        60, 
        45,
        facecolor='green',
        edgecolor='green'
    )
)
plt.draw()
plt.show()

But nothings of the patch shows up. Also tested to use time directly, it actually ran but no patch was rendered.

plt.Rectangle(
    (0,datetime_D), 
    60, 
    4*pandas.datetools.Minutes(15),
    facecolor='green',
    edgecolor='green'
)

What is the underlying type? How should I position things in time in matplotlib? Any uglyhack working is appreciated.

like image 516
SlimJim Avatar asked Sep 04 '12 09:09

SlimJim


People also ask

How do I draw a square in MatPlotLib?

We can generate a square plot using matplotlib. axes. Axes. set_aspect() method.


1 Answers

You seem to have swapped x and y as first argument of Rectangle((x,y), ...).
Rectangle((22395760, 0), ...)

Instead of using a patch, plot.axvspan() seems a better match for what you want to do.

plt.gca().axvspan(date,date+2*pandas.datetools.Minute(15),facecolor='green',edge‌ color='green',alpha=0.3)
like image 197
Wouter Overmeire Avatar answered Nov 04 '22 14:11

Wouter Overmeire