简体   繁体   English

使用 python 中的长格式数据创建时间序列 plot?

[英]Creating a time-series plot with data in long format in python?

I have time-series data in a pandas DataFrame that looks like this:我在 pandas DataFrame中有时间序列数据,如下所示:

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

And I want to create a separate line plot for each of the distinct IDs (ie patients).我想为每个不同的 ID(即患者)创建一个单独的行 plot。 How can I go about this preferably using matplotlib?我如何最好使用 matplotlib 来解决这个问题? Will I have to create a "time-interval" variable?我必须创建一个“时间间隔”变量吗?


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

However, as I get the following error:但是,当我收到以下错误时:

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

Just groupby and plot it:只需groupby和 plot 它:

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

Or using multiple axes, without worrying (so much at least) with the size of the category:或者使用多个轴,而不用担心(至少这么多)类别的大小:

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

Output: Output:

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM