【问题标题】:Pandas Multiple Time Series Plots Single Data FramePandas 多个时间序列绘制单个数据帧
【发布时间】:2022-01-06 15:15:42
【问题描述】:

鉴于以下pandasDataFrame,显示具有每个名称类别的离散时间桶的时间序列图的惯用方式是什么?

Name Type
time datetime64
name object
value float64

我当前的解决方案需要一个循环来提取 DataFrame 并为每个名称类别计算 max 聚合。

import pandas as pd
import matplotlib.pyplot as plt

raw_df = pd.read_csv('...')
raw_df['time'] = raw_df['time'].astype('datetime64[ns]')

names = raw_df['name'].unique()
names.sort()

fig, ax = plt.subplots()

for name in names:
    df = raw_df.query(f'name == "{name}"').set_index('time').resample('10T').max()
    df.plot(ax = ax, label=name)

【问题讨论】:

  • sns.lineplot(data=raw_df, x='time', y='value', hue='name') seaborn 是 matplotlib 的高级 api

标签: python pandas dataframe matplotlib time-series


【解决方案1】:

你可以使用:

df.pivot(index='time', values='value', columns='name').resample('10Y').max().plot(subplots=True)

例子:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({
    'name': np.append(np.repeat('a', 50), np.repeat('b', 50)),
    'time': pd.to_datetime(2 * pd.date_range(start='1950-01-01', periods=50, freq='Y').values.tolist()),
    'value': np.append(np.cumsum(np.random.lognormal(0, 1, 50)), np.cumsum(np.random.lognormal(0, 1, 50)))
})

df.pivot(index='time', values='value', columns='name').resample('10Y').max().plot(subplots=True)

另见this answer

【讨论】:

    猜你喜欢
    • 2011-09-30
    • 1970-01-01
    • 2016-02-22
    • 1970-01-01
    • 2020-12-04
    • 2016-11-06
    • 2019-07-08
    • 2017-10-26
    • 1970-01-01
    相关资源
    最近更新 更多