Reputation: 616
I created a matplotlib plot with x-data being DateTimes.
I want to shade certain areas of the chart, like the entire chart area between 7 and 10 am. I attempted to do something similar below, shading the entire area right of some value.
I am not getting any errors, but my chart is not showing any shading.
Could you please assist?
df = pd.read_csv(path)
df['DateTime2'] = pd.to_datetime(df['DateTime'])
df['Time'] = pd.to_datetime(df['DateTime']).dt.time
sns.set_palette('muted')
x = df['DateTime2']#.values
fig, ax1 = plt.subplots(figsize=(12, 6))
fig.patch.set_facecolor('grey')
ax1.plot(x, df[[col for col in df.columns if 'level' in col]])
ax1.set_xlabel('Time of day')
ax1.set_ylabel('Dam level (%)')
ax1.set_ylim([0, 100])
ax2 = ax1.twinx()
ax2.plot(x, df[[col for col in df.columns if 'status' in col]])
ax2.set_ylabel('Pump status')
ax2.yaxis.set_major_locator(MaxNLocator(integer=True))
ax1.xaxis.set_major_locator(mdates.HourLocator())
ax1.xaxis.set_minor_locator(mdates.MinuteLocator(byminute=30))
ax1.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M'))
fig.autofmt_xdate(rotation=90)
ax1.set_xlim((min(x),max(x)))
y = df[[col for col in df.columns if 'level' in col]]
x2 = pd.to_numeric(x.values)
x2_mask = np.ma.masked_greater_equal(x2, 990002640000000000).mask
ax1.fill_between(x2, 0, 100, where=x2_mask, facecolor='red')
ax1.grid(which='major', alpha=0.5)
ax1.grid(which='minor', alpha=0.25)
ax2.grid(which='major', alpha=0.5)
#ax1.minorticks_on()
fig.tight_layout()
plt.show()
fig.savefig('output.png')
plt.close('all')
Expected output:
Something like:
But with the red behind the lines
Paint skills for the win!
Script: https://hastebin.com/oyegaceneq.py
Data: https://hastebin.com/enabiguxan.csv (save as csv)
Upvotes: 0
Views: 501
Reputation: 153500
Try something like this with axvspan
:
ax2.axvspan('2001-05-16 07:00:00','2001-05-16 10:00:00',alpha=.5,color='red')
ax2.axvspan('2001-05-16 16:00:00','2001-05-16 20:00:00',alpha=.5,color='red')
Upvotes: 1