python - Pandas 必须标记所有对象,否则图例错误?
问题描述
当我想通过 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,这样颜色才能正确?
它是否存在某些方式我可以展示一些传说并使其他人不可见?
解决方案
一种方法:在显示其他对象之前将所有需要图例的对象
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')
推荐阅读
- macos - Expo CLI 安装后需要安装 (macOs)
- machine-learning - 如何为预训练模型编写评估函数并指定数据加载器?
- javascript - 无论如何我可以在使用 papaparse 将 json 转换为 csv 时连续获取标题
- java - 即使 Activity 在后台,如何显示 AlertDialog?
- laravel - 如何在 Vue.js 中对我的数据的输入应用用户过滤器?
- sql - 在存储过程中将日期强制为每月的第一天
- node.js - Try-catch 没有捕捉到 .then().catch() 抛出的错误
- aws-lambda - Cognito Lambda 授权方如何根据用户限制对 Lambda 的访问
- android - 如何查看芯片组中的所有芯片?
- python - 如何在 Spark 中使用 Python 查找 DataFrame 中的分区数以及如何在 Spark 中使用 Python 在 DataFrame 中创建分区