首页 > 解决方案 > Pandas 必须标记所有对象,否则图例错误?

问题描述

图片和代码来自 https://www.statsmodels.org/stable/examples/notebooks/generated/exponential_smoothing.html#Exponential-smoothing

当我想通过 Pandas 显示图例时出现问题,我无法显示其中一些,或者图例的颜色会错误。

在“简单指数平滑”部分

import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from statsmodels.tsa.api import ExponentialSmoothing, SimpleExpSmoothing, Holt

data = [446.6565,  454.4733,  455.663 ,  423.6322,  456.2713,  440.5881, 425.3325,  485.1494,  506.0482,  526.792 ,  514.2689,  494.211 ]
index= pd.date_range(start='1996', end='2008', freq='A')
oildata = pd.Series(data, index)

ax=oildata.plot()
ax.set_xlabel("Year")
ax.set_ylabel("Oil (millions of tonnes)")
plt.show()
print("Figure 7.1: Oil production in Saudi Arabia from 1996 to 2007.")

fit1 = SimpleExpSmoothing(oildata).fit(smoothing_level=0.2,optimized=False)
fcast1 = fit1.forecast(3).rename(r'$\alpha=0.2$')
fit2 = SimpleExpSmoothing(oildata).fit(smoothing_level=0.6,optimized=False)
fcast2 = fit2.forecast(3).rename(r'$\alpha=0.6$')
fit3 = SimpleExpSmoothing(oildata).fit()
fcast3 = fit3.forecast(3).rename(r'$\alpha=%s$'%fit3.model.params['smoothing_level'])

ax = oildata.plot(marker='o', color='black', figsize=(12,8))
fcast1.plot(marker='o', ax=ax, color='blue', legend=True)
fit1.fittedvalues.plot(marker='o', ax=ax, color='blue')
fcast2.plot(marker='o', ax=ax, color='red', legend=True)
fit2.fittedvalues.plot(marker='o', ax=ax, color='red')
fcast3.plot(marker='o', ax=ax, color='green', legend=True)
fit3.fittedvalues.plot(marker='o', ax=ax, color='green')
plt.show()

结果图片

注意图例的颜色是错误的

但是,如果我像这样更改 fit1,2 和 3:

...
fit1.fittedvalues.plot(marker='o', ax=ax, color='blue',legend=True)#to make every line legend True
fcast2.plot(marker='o', ax=ax, color='red', legend=True)
...

新图例运行良好。(两个图例颜色相同除外)

所以问题是,如果我想显示 Pandas 情节的图例,我必须使所有线条(或对象)图例为 True,这样颜色才能正确?

它是否存在某些方式我可以展示一些传说并使其他人不可见?

标签: pythonpandaslegend

解决方案


一种方法:在显示其他对象之前将所有需要图例的对象

fcast1.plot(marker='o', ax=ax, color='blue', legend=True)
fcast2.plot(marker='o', ax=ax, color='red', legend=True)
fcast3.plot(marker='o', ax=ax, color='green', legend=True)
fit1.fittedvalues.plot(marker='o', ax=ax, color='blue')
fit2.fittedvalues.plot(marker='o', ax=ax, color='red')
fit3.fittedvalues.plot(marker='o', ax=ax, color='green')

推荐阅读