【问题标题】:Multiple multi-line plots group wise in PythonPython中的多个多线图分组明智
【发布时间】:2021-06-01 02:55:45
【问题描述】:

我有一个这样的熊猫数据框 - (创建一个随机数据框)

from random import randint
from random import random
import random
import pandas as pd

x = [randint(1,20) for i in range(20)]
y1 = [random() for i in range(20)]
y2 = [random() for i in range(20)]
y3 = [random() for i in range(20)]
y4 = [random() for i in range(20)]
g = ['a', 'b', 'c']

group = [random.choice(g) for i in range(20)]
data = {'Group': group, 'x': x, 'y1':y1, 'y2':y2, 'y3':y3, 'y4':y4}

df = pd.DataFrame(data)
df.sort_values('Group')

数据框是这样的-

>>> df.sort_values('Group')
   Group   x        y1        y2        y3        y4
17     a   9  0.400730  0.242629  0.858307  0.799613
16     a  14  0.644299  0.952255  0.257262  0.376845
5      a   3  0.784374  0.800639  0.753612  0.441645
18     a   3  0.988016  0.739003  0.741000  0.299011
11     a  18  0.672816  0.232951  0.763451  0.762478
0      b   7  0.670889  0.785928  0.604563  0.620951
15     b   3  0.838479  0.286988  0.374546  0.013822
4      b   4  0.495855  0.159839  0.984262  0.882428
13     b   3  0.756058  0.979226  0.423426  0.297381
8      b  13  0.835705  0.374927  0.492676  0.939113
12     b  17  0.643511  0.156267  0.248037  0.316526
14     c  13  0.303215  0.177303  0.980071  0.705428
9      c  16  0.829414  0.173755  0.992532  0.398509
7      c   9  0.774353  0.082118  0.089582  0.587679
6      c  14  0.551595  0.737882  0.127206  0.985017
3      c   4  0.072765  0.497016  0.634819  0.149798
2      c   1  0.971598  0.254215  0.325086  0.588159
1      c  14  0.467277  0.631844  0.927199  0.051251
10     c  13  0.346592  0.384929  0.185384  0.330408
19     c  16  0.790785  0.449498  0.176042  0.036896

使用此数据框,我打算按组绘制多个图(在本例中为 3 个图,因为只有 3 个组)。每个图都是一个多线图,x 轴上是x,y 轴上是[y1, y2, y3, y4]

我怎样才能做到这一点,我可以绘制单个多线图,但无法按组绘制多个图。

【问题讨论】:

    标签: python pandas matplotlib seaborn


    【解决方案1】:

    你可以使用groupby:

    fig, axes = plt.subplots(1, 3, figsize=(10,3))
    for (grp, data), ax in zip(df.groupby('Group'), axes.flat):
        data.plot(x='x', ax=ax)
    

    输出:

    注意:您实际上不需要按组排序。

    【讨论】:

    • 我如何指定列而不是axes.flat
    • 指定列是什么意思?您的问题中似乎没有列出。
    • 除了 y1,y2,y3 和 y4 我在 df 中有更多列 - 但我想我会删除它们并执行此操作。我在网格布局上遇到问题,因为通常没有 3 个组。有时组可以在 20 人左右,有时甚至 40 人。那么我该如何安排布局呢?
    • 将 'y=['y1',...]` 传递给 .plot。您需要知道len(df['Group'].unique()) 有多少组并设置布局。您也可以使用seaborn 作为 groupby 的替代方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-04
    相关资源
    最近更新 更多