【问题标题】:Plot multiple years in chart overlapping the other在图表中绘制多年重叠的年份
【发布时间】:2019-12-04 03:09:32
【问题描述】:

我有一个包含超过 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

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

我尝试过这样的事情,但一年又一年

  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()

【问题讨论】:

  • 将日期转换为 dayofyear 并以 dayofyear 作为 xaxis 绘制每个系列(年)。
  • 那么你要2001, 2002, ..., 2019中的数据在同一张图表中,每年都有一条线吗?
  • 是的,每年在同一个图表中作为独立行

标签: python pandas plot


【解决方案1】:

正如 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);

【讨论】:

    【解决方案2】:

    我稍作改动,使用日期作为索引

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多