pandas - 多索引 DataFrame 的多面图

标签 pandas seaborn

如何使用 pandas 和 seaborn 绘制每个 channel (应用内、电子邮件、推送)的三个时间序列,其色调随“启用”而变化?请注意,这些列是多重索引的。我希望这些图共享 y 轴并有一个共同的图例来指示“启用”的值。

|---------|---------------|--------------|---------------|
| channel | inapp         | email        | push          |
| enabled | true  | false | false | true | false | true  |
|---------|-------|-------|-------|------|-------|-------|
| 0       | 0     | 80    | 28    | 0    | 5     | 0     |
| 1       | 2     | 80    | 28    | 3    | 5     | 233   |
| 2       | 4     | 80    | 28    | 7    | 5     | 587   |
| 3       | 5     | 80    | 28    | 12   | 5     | 882   |
| 4       | 7     | 86    | 28    | 16   | 5     | 1292  |
|---------|-------|-------|-------|------|-------|-------|

最佳答案

这是另一种方法,使用 Paul H 的 .stack() 方法(尽管我也无法使用 FacetGrid 弄清楚):

import pandas as pd
from matplotlib import pyplot as plt

enabled = [True, False]
channel =['inapp','email','push']
values = [0,2,4,5,7,80,80,80,80,86,28,28,28,28,28,
          0,3,7,12,16,5,5,5,5,5,0,233,587,882,1292]
values = np.array(values).reshape((5,6), order='F')

columns = pd.MultiIndex.from_product([channel,enabled], names=("channel","enabled"))
df = pd.DataFrame(values, columns=columns)

fig, ax = plt.subplots(1,3,sharey=True)

for i, (key, group) in enumerate(df.stack(level='channel').reset_index(level=1).groupby('channel')):
    group.plot(label=key, title=key, ax=ax[i])

更新:
这是一个更紧凑的版本,使用 unstack()factorplot()
rename 行只是为了使情节清晰,可以将其删除。

df = (df.unstack('enabled')
        .reset_index()
        .rename(columns={'level_2':'time',0:'value'})
)
sns.factorplot(data=df, x='time', y='value', hue='enabled', col='channel')

timeseries plot

关于pandas - 多索引 DataFrame 的多面图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43461733/

相关文章:

Python pandas 计算日期之间的距离

python - timedelta csv Pandas

python - 尝试将颜色条添加到 Seaborn 散点图

python - 如何并排绘制 2 个 seaborn lmplots?

python - 在循环seaborn图中共享次要y轴

python - 使用最近的行填充数据框中的缺失值

python - 将 df1 列值替换为 df2 列值 - df-1 column-3 的值是 df-2 的列

python - 计算数据框中特定列中的特定值?

pandas - 无法在seaborn中创建对角直方图

Seaborn 散点图自定义图例显示单个标签