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:

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 (i.e. patients). How can I go about this preferably using 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'

Answer

Just groupby and plot it:

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:

enter image description here

Leave a Reply

Your email address will not be published. Required fields are marked *