Python 如何根据特定日期为图表着色?

Python 如何根据特定日期为图表着色?,python,matplotlib,graph,Python,Matplotlib,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 delt

让我们以这个样本数据和这个图表为例:

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()

我想给图表中预测值的部分上色(黑线右侧)。我假设我必须使用
fill\u-between
功能,但我无法达到我的目标。我该怎么办

预期输出(使用PowerPoint手动完成):


尝试使用matplotlib.pyplot.axvspan(xmin,xmax,ymin=0,ymax=1,hold=None,**kwargs)跨轴添加垂直跨度(矩形),如下所示:

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()
输出:


这个问题应该能够帮助您: