在图表中绘制与其他年份重叠的多年

时间:2019-07-25 19:10:15

标签: python pandas plot

我有一个数据框,其中包含20多年的库存数据。

Open    High    Low Close   Adj Close   Volume
Date                        
2001-01-02  1.062500    1.089286    1.040179    1.062500    0.930781    113078000
2001-01-03  1.035714    1.191964    1.031250    1.169643    1.024641    204268400
2001-01-04  1.295759    1.321429    1.200893    1.218750    1.067660    184849000
2001-01-05  1.209821    1.241071    1.147321    1.169643    1.024641    103089000
2001-01-08  1.209821    1.213170    1.138393    1.183036    1.036374    93424800

我想要的是在同一张图表中分别绘制每年(价格),从1月开始,到12月结束。

我尝试了类似的方法,但又一年又一次地密谋

  for year in range(2001,2019):
    aapl['Close'].loc[str(year)].plot(figsize=(18,8), label=str(year), secondary_y=True)
plt.legend()
plt.show()

2 个答案:

答案 0 :(得分:0)

如Scott所言,您可以针对dayofyear绘制系列,而seaborn可以帮助您在一排中做到这一点:

# convert to datetime if not already is
df['Date'] = pd.to_datetime(df['Date'])

# plot:    
sns.lineplot(x=df['Date'].dt.dayofyear, 
             y=df['Close'], 
             hue=df['Date'].dt.year);

答案 1 :(得分:0)

我做了一些更改以将日期用作索引

sns.lineplot(x=aapl.index.dayofyear, 
             y=aapl['Close'], 
             hue=aapl.index.year)

*注:sns.lineplot在seaborn 0.9之后开始工作