【问题标题】:Creating a time-series plot with data in long format in python?在 python 中使用长格式数据创建时间序列图?
【发布时间】:2021-06-15 08:46:25
【问题描述】:

我在 pandas DataFrame 中有时间序列数据,如下所示:

ID  HeartRate
1      120
1      118
1      115
2      98
2      110
2      112
3      128
3      115
3      90

我想为每个不同的 ID(即患者)创建一个单独的线图。我怎样才能最好地使用matplotlib呢?我需要创建一个“时间间隔”变量吗?


df = my_data[['ID', 'HR']].copy() ## creating a new "mini" dataframe from the larger one that I've got. 

n_ids = df.ID.unique().size 
n_cols = int(n_ids ** 0.5) 
n_rows = int(n_ids + n_ids % n_cols) 
fig, axes = plt.subplots(n_rows, n_cols) 
for i, (ids, hr) in enumerate(df.groupby('ID')['HR']): 
hr.plot(ax=axes[i], title=f"ID:{idx}") 
fig.tight_layout()

但是,当我收到以下错误时:

'numpy.ndarray' object has no attribute 'get_figure'

【问题讨论】:

  • 您愿意使用pandas 库吗?
  • 是的,很抱歉忘记提及我的数据集已作为 pandas 数据框导入
  • 这能回答你的问题吗? Plotting grouped data in same plot using Pandas
  • 分开是指不同ax上的每个ID?
  • 我不认为它确实如此,因为据我所知,他们正在那里的一个地块上绘制不同的不同单位,而我想做的是相反的(除非我错过了线程中有东西!)

标签: python pandas matplotlib plot time-series


【解决方案1】:

只需 groupby 并绘制它:

df.groupby('ID')['HeartRate'].plot()

或者使用多个轴,而不用担心(至少这么多)类别的大小:

n_ids = df.ID.unique().size
n_cols = int(n_ids ** 0.5)
n_rows = n_cols + (1 if n_ids % n_cols else 0)                   
fig, axes = plt.subplots(n_rows, n_cols)
axes = axes.ravel()
for i, (idx, series) in enumerate(df.groupby('ID')['HeartRate']):
    series.plot(ax=axes[i], title=f"ID:{idx}")
fig.tight_layout()

输出:

【讨论】:

  • 但是运行这段代码,所有的折线图都在示例图中。相反,我试图为每个不同的 ID 创建一个不同的图。
  • 不,我为每个情节版本添加了一个 ID。
  • 是的,这正是我想要的——抱歉,我可能第一次错过了那段代码。但是,当我运行代码时,出现以下错误:AttributeError: 'numpy.ndarray' object has no attribute 'get_figure' - 知道为什么会发生这种情况吗?
  • 你能发布确切的代码吗?您可能会将阵列与斧头混合使用。无论如何,如果你已经在我展示给你的代码中拥有它,为什么还要get_figure
  • 比如axes[0].get_figure()就可以了。
猜你喜欢
  • 2021-08-19
  • 2016-08-21
  • 1970-01-01
  • 1970-01-01
  • 2020-11-06
  • 2019-09-20
  • 1970-01-01
  • 2015-09-19
  • 2022-11-16
相关资源
最近更新 更多