Reputation: 935
Let's take this sample data and this graph :
import pandas as pd
import numpy as np
from datetime import date, timedelta
from matplotlib import pyplot as plt
# Creating sample data
DataX = []
sdate = date(2020, 6, 30) # start date
edate = date(2020, 7, 30) # end date
delta = edate - sdate # as timedelta
for i in range(delta.days + 1):
day = sdate + timedelta(days=i)
DataX.append(day)
N = list(range(len(DataX)))
DataY1 = np.exp(N)
DataY2 = np.sin(N)
# create figure and axis objects with subplots()
fig,ax = plt.subplots(figsize=(20,8))
# make a plot
ax.plot(DataX, DataY1, color="red", marker="o")
# set x-axis label
ax.set_xlabel("date",fontsize=14)
# set y-axis label
ax.set_ylabel("Y1",color="red",fontsize=14)
# twin object for two different y-axis on the sample plot
ax2=ax.twinx()
# make a plot with different y-axis using second axis object
ax2.plot(DataX, DataY2,color="blue",marker="o")
ax2.set_ylabel("Y2",color="blue",fontsize=14)
plt.axvline(x=date.today(),color='k', linestyle='--')
plt.title("title")
#plt.savefig("stck_color_predict")
plt.show()
I would like to color the part of the graph where values are predicted (right of the black line). I assume I have to use the fill_between
function but I can't reach my goal. How please could I do ?
Expected output (manually done with PowerPoint) :
Upvotes: 1
Views: 399
Reputation: 917
Try using matplotlib.pyplot.axvspan(xmin, xmax, ymin=0, ymax=1, hold=None, **kwargs) to add a vertical span (rectangle) across the axes, as follow:
import pandas as pd
import numpy as np
from datetime import date, timedelta
from matplotlib import pyplot as plt
# Creating sample data
DataX = []
sdate = date(2020, 6, 30) # start date
edate = date(2020, 7, 30) # end date
delta = edate - sdate # as timedelta
for i in range(delta.days + 1):
day = sdate + timedelta(days=i)
DataX.append(day)
N = list(range(len(DataX)))
DataY1 = np.exp(N)
DataY2 = np.sin(N)
# create figure and axis objects with subplots()
fig, ax = plt.subplots(figsize=(20, 8))
# make a plot
ax.plot(DataX, DataY1, color="red", marker="o")
# set x-axis label
ax.set_xlabel("date", fontsize=14)
# set y-axis label
ax.set_ylabel("Y1", color="red", fontsize=14)
# twin object for two different y-axis on the sample plot
ax2 = ax.twinx()
# make a plot with different y-axis using second axis object
ax2.plot(DataX, DataY2, color="blue", marker="o")
ax2.set_ylabel("Y2", color="blue", fontsize=14)
plt.axvline(x=date.today(), color='k', linestyle='--')
plt.title("title")
plt.axvspan(date.today(), edate, facecolor='b', alpha=0.5)
# plt.savefig("stck_color_predict")
plt.show()
Output:
Upvotes: 1