pandas - 循环问题的 Matplotlib 图
问题描述
我正在尝试使用 for 循环在 matplotlib 中绘制时间序列数据。目标是动态绘制价值“n”年的每日收盘价数据。如果我加载 7 年的数据,我会得到 7 个独特的图。我创建了一个数据集 yearly_date_ranges 的开始和结束日期的摘要(日期是索引)。我用它来填充开始和结束日期。到目前为止,我编写的代码生成了所有每日数据的 7 个图,而不是 7 个独特的图,每年一个。任何帮助表示赞赏。提前致谢!
yearly_date_ranges
start end
Date
2014 2014-04-01 2014-12-31
2015 2015-01-01 2015-12-31
2016 2016-01-01 2016-12-31
2017 2017-01-01 2017-12-31
2018 2018-01-01 2018-12-31
2019 2019-01-01 2019-12-31
2020 2020-01-01 2020-05-28
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
fig = plt.figure(figsize=(12,20))
for i in range(len(yearly_date_ranges)):
ax = fig.add_subplot(len(yearly_date_ranges),1,i + 1)
for row in yearly_date_ranges.itertuples(index=False):
start = row.start
end = row.end
subset = data[start:end]
ax.plot(subset['Close'])
plt.show()
解决方案
这行得通!感谢您的帮助
fig, axes = plt.subplots(7,1, figsize=(12,20))
years = data.index.year
for ax, (k,d) in zip(axes.ravel(), data['Close'].groupby(years)):
d.plot(x='Close', ax=ax)
推荐阅读
- mongodb - Mongo 连接字符串问题 - 主机为空
- android - 如何在 Android sip stack SipManager 中拨打我的手机号码?
- java - 如何区分呼叫是移动呼叫还是IP呼叫?
- excel - Excel中带有字符串变量的间接函数
- java - 使用 Jackson 对类扩展进行 Json 反序列化的问题 - 未找到类型返回值的转换器
- ansible - 如何传递第二个列表进行播放
- javascript - 以角度使用 ViewChild() 获取元素
- logging - 在 RavenDB 中保存结构化日志
- bdd - 一个场景大纲中多个步骤的最佳实践
- google-chrome - 身份验证后,重定向到 PWA UI 显示的是服务工作者代码