【问题标题】:How to color a graph from a specific date?如何为特定日期的图表着色?
【发布时间】:2020-07-21 11:42:13
【问题描述】:

让我们来看看这个样本数据和这个图表:

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_between 函数,但我无法达到我的目标。请问我该怎么办?

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

【问题讨论】:

标签: python matplotlib graph


【解决方案1】:

尝试使用 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()

输出:

【讨论】:

    猜你喜欢
    • 2020-03-21
    • 2016-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-14
    • 1970-01-01
    相关资源
    最近更新 更多