You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改fbprophet预测图中预测线与置信区间阴影颜色为deeppink

fbprophet预测图统一修改预测线、置信区间颜色方法

问题场景

使用fbprophet开展时间序列预测时编写的初始代码如下:

from fbprophet import Prophet
from pandas import to_datetime
df=df_date_pink[["Date of Travel",'Number of Passengers']]
df.columns = ['ds', 'y']
df['ds']= to_datetime(df['ds'])
model = Prophet()
model.fit(df)
future = list()
for i in range(1, 13):
    date = '2019-%02d' % i
    future.append([date])
future = pd.DataFrame(future)
future.columns = ['ds']
future['ds']= to_datetime(future['ds'])
forecast = model.predict(future)
print(forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].head())
model.plot(forecast)
plt.gca().get_lines()[0].set_color("deeppink")
plt.title("Pink Cabs Number of Passengers and Its Forecast For The Next Year", size=15)
plt.xlabel("Dates", size=15)
plt.ylabel("Number of Passengers", size=15)
plt.show()

代码运行生成的可视化效果如下:
代码运行生成的可视化效果
初始代码仅完成了实际观测值折线的deeppink颜色设置,需要将预测值折线、阴影形式的置信区间区域也统一设置为deeppink。

实现方案

fbprophet调用plot()方法生成的图表中,不同元素对应坐标轴下的固定索引对象,直接修改对应属性即可实现颜色统一:

  • 索引0的line对象:实际观测值序列
  • 索引1的line对象:预测值(yhat)折线
  • 索引0的collection对象:置信区间的填充阴影区域

操作时建议先接收plot()返回的画布对象再做修改,避免直接调用plt.gca()出现索引匹配错误,同时给置信区间填充设置0.2左右的透明度,和原生阴影的视觉效果保持一致,避免颜色过深遮挡其他内容。
修改后的可运行完整代码:

from fbprophet import Prophet
from pandas import to_datetime
import pandas as pd
import matplotlib.pyplot as plt

df=df_date_pink[["Date of Travel",'Number of Passengers']]
df.columns = ['ds', 'y']
df['ds']= to_datetime(df['ds'])
model = Prophet()
model.fit(df)

future = list()
for i in range(1, 13):
    date = '2019-%02d' % i
    future.append([date])
future = pd.DataFrame(future)
future.columns = ['ds']
future['ds']= to_datetime(future['ds'])
forecast = model.predict(future)
print(forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].head())

# 获取画布与坐标轴对象
fig = model.plot(forecast)
ax = fig.gca()

# 统一设置所有元素为deeppink
ax.lines[0].set_color("deeppink")  # 实际观测值
ax.lines[1].set_color("deeppink")  # 预测值折线
ax.collections[0].set_facecolor("deeppink")  # 置信区间填充
ax.collections[0].set_alpha(0.2)  # 调整填充透明度

plt.title("Pink Cabs Number of Passengers and Its Forecast For The Next Year", size=15)
plt.xlabel("Dates", size=15)
plt.ylabel("Number of Passengers", size=15)
plt.show()

运行代码后,实际观测值、预测折线、置信区间阴影会统一为深粉色系,风格匹配。


内容的提问来源于stack exchange,提问作者Efe Karasil Student

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.02 03:01:17