【问题标题】:Pandas groupby results on the same plotPandas groupby 结果在同一图上
【发布时间】:2020-10-15 13:28:13
【问题描述】:

我正在处理以下数据框(仅作说明,实际df很大):

   seq          x1         y1
0  2           0.7725      0.2105
1  2           0.8098      0.3456
2  2           0.7457      0.5436
3  2           0.4168      0.7610
4  2           0.3181      0.8790
5  3           0.2092      0.5498
6  3           0.0591      0.6357
7  5           0.9937      0.5364
8  5           0.3756      0.7635
9  5           0.1661      0.8364

尝试为上述坐标绘制多条线图(x 为“x1”,y 为“y1”)。

具有相同“seq”的行是一条路径,并且必须绘制为一条单独的线,就像 seq = 2 对应的所有 x、y 坐标属于一条线,依此类推。

我可以绘制它们,但在单独的图表上,我希望所有线都在同一个图表上,使用 subplots,但不正确。

import matplotlib as mpl
import matplotlib.pyplot as plt

%matplotlib notebook

df.groupby("seq").plot(kind = "line", x = "x1", y = "y1")

这会创建 100 个图(等于唯一序列的数量)。建议我一种获取同一图表上所有线条的方法。

**更新*

为了解决上述问题,我实现了以下代码:

     fig, ax = plt.subplots(figsize=(12,8))
     df.groupby('seq').plot(kind='line', x = "x1", y = "y1", ax = ax)
     plt.title("abc")
     plt.show()

现在,我想要一种用特定颜色绘制线条的方法。我正在集群 1 中的 seq = 2 和 5 的集群路径;和来自 seq = 3 的路径在另一个集群中。

所以,集群 1 下有两行我想要红色,集群 2 下有 1 行可以是绿色。

我应该怎么做?

【问题讨论】:

标签: python pandas matplotlib


【解决方案1】:

你需要像这个例子一样在绘图之前初始化轴

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

# random df
df = pd.DataFrame(np.random.randint(0,10,size=(25, 3)), columns=['ProjID','Xcoord','Ycoord'])

# plot groupby results on the same canvas 
fig, ax = plt.subplots(figsize=(8,6))
df.groupby('ProjID').plot(kind='line', x = "Xcoord", y = "Ycoord", ax=ax)
plt.show()

【讨论】:

  • 非常感谢,这正是我想要的。
  • 这很好,但是如果我想让图例列出 ProjID 列值而不是“Ycoord”呢?
  • @autonomy 你必须在一个循环中绘制 groupby 的结果,并使用 plot 函数的 label 参数分别为每一行设置图例文本。您可能会在 bernie 的下一个答案中找到循环示例
  • @Serenity 谢谢,这就是我最终做的,猜它是 2 行而不是单行: fig, ax = plt.subplots(figsize=(18,16)) for id, group在 seq_data.groupby('id'): group.plot(y='timestamp', x='xpos', title='X-position vs. time', ax=ax, label=id)
【解决方案2】:

考虑数据框df

df = pd.DataFrame(dict(
        ProjID=np.repeat(range(10), 10),
        Xcoord=np.random.rand(100),
        Ycoord=np.random.rand(100),
    ))

然后我们像这样创作抽象艺术

df.set_index('Xcoord').groupby('ProjID').Ycoord.plot()

【讨论】:

    【解决方案3】:

    另一种方式:

    for k,g in df.groupby('ProjID'):
      plt.plot(g['Xcoord'],g['Ycoord'])
    
    plt.show()
    

    【讨论】:

      【解决方案4】:

      这是一个工作示例,包括调整图例名称的功能。

      grp = df.groupby('groupCol')
      
      legendNames = grp.apply(lambda x: x.name)  #Get group names using the name attribute.
      #legendNames = list(grp.groups.keys())  #Alternative way to get group names. Someone else might be able to speak on speed. This might iterate through the grouper and find keys which could be slower? Not sure
      
      plots = grp.plot('x1','y1',legend=True, ax=ax)
      
      for txt, name in zip(ax.legend_.texts, legendNames):
          txt.set_text(name)
      

      说明: 图例值存储在参数 ax.legend_ 中,该参数又包含一个 Text() 对象列表,每组一个项目,其中 Text 类位于 matplotlib.text api 中。要设置文本对象的值,可以使用 setter 方法 set_text(self, s)。

      附带说明,Text 类有许多 set_X() 方法,可让您更改字体大小、字体、颜色等。我没有使用过这些,所以我不确定它们工作,但不明白为什么不。

      【讨论】:

        【解决方案5】:

        基于Serenity的anwser,我将传说做得更好。

        import pandas as pd
        import matplotlib.pylab as plt
        import numpy as np
        
        # random df
        df = pd.DataFrame(np.random.randint(0,10,size=(25, 3)), columns=['ProjID','Xcoord','Ycoord'])
        
        # plot groupby results on the same canvas 
        grouped = df.groupby('ProjID')
        fig, ax = plt.subplots(figsize=(8,6))
        grouped.plot(kind='line', x = "Xcoord", y = "Ycoord", ax=ax)
        ax.legend(labels=grouped.groups.keys()) ## better legend
        plt.show()
        

        你也可以这样做:

        grouped = df.groupby('ProjID')
        fig, ax = plt.subplots(figsize=(8,6))
        g_plot = lambda x:x.plot(x = "Xcoord", y = "Ycoord", ax=ax, label=x.name)
        grouped.apply(g_plot)
        plt.show()
        

        它看起来像:

        【讨论】:

          猜你喜欢
          • 2013-03-06
          • 2013-07-14
          • 1970-01-01
          • 2014-08-08
          • 1970-01-01
          • 2015-06-20
          • 2018-02-24
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多