10

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?

Hound
  • 932
  • 2
  • 17
  • 26

1 Answers1

14

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()
Ffisegydd
  • 51,807
  • 15
  • 147
  • 125
  • Ok that makes a lot more sense now. Thank you very much. – Hound Apr 10 '15 at 18:26
  • 1
    I have been looking for a way to use Matplotlib figure methods on plots made with pandas. The fig, ax = plt.subplots() and then plotting with ax=ax gave the link I needed. Thank you! – BLimitless Feb 28 '21 at 15:12