Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use ax with Pandas and Matplotlib

I have a very basic question. I am using a pandas dataframe to make this plot, but I want to add highlighting around certain dates.

In[122]:
df1_99.plot(x='date', y='units', ylim=[0,11], figsize=[12,12])

Out[122]: enter image description here

I found this code on stackoverflow to add highlighting.

fig, ax = plt.subplots()
ax.plot_date(t, y, 'b-')
ax.axvspan(*mdates.datestr2num(['10/27/2011', '11/2/2011']), color='red', alpha=0.5)
fig.autofmt_xdate()
plt.show()

My question is how can I use ax.avxspan with my current code? Or do I need to convert my x='date', and y='units' to numpy arrays and use the format as in the code above?

like image 707
Hound Avatar asked Apr 10 '15 18:04

Hound


People also ask

Can you use matplotlib with pandas?

Matplotlib is an amazing python library which can be used to plot pandas dataframe.

How do you label axes in pandas plot?

With Pandas plot() , labelling of the axis is achieved using the Matplotlib syntax on the “plt” object imported from pyplot. The key functions needed are: “xlabel” to add an x-axis label. “ylabel” to add a y-axis label.


1 Answers

pandas.DataFrame.plot will return the matplotlib AxesSubplot object.

ax = df1_99.plot(x='date', y='units', ylim=[0,11], figsize=[12,12])

ax.axvspan(*mdates.datestr2num(['10/27/2011', '11/2/2011']), color='red', alpha=0.5)
plt.show()

If you want to create an ax object in advance, you can pass it into plot as below

fig, ax = plt.subplots()

df1_99.plot(x='date', y='units', ylim=[0,11], figsize=[12,12], ax=ax)

ax.axvspan(*mdates.datestr2num(['10/27/2011', '11/2/2011']), color='red', alpha=0.5)
plt.show()

Finally, you can usually get the current figure and axes objects using the following functions

fig = plt.gcf()
ax = plt.gca()
like image 161
Ffisegydd Avatar answered Oct 13 '22 12:10

Ffisegydd