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]:
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?
Matplotlib is an amazing python library which can be used to plot pandas dataframe.
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With