首页 > 解决方案 > 在循环中绘制 DataFrameGroupBy 对象会给出多个图

问题描述

继上一个问题之后,我对 matplotlib.pyplot 的工作方式感到困惑。我有一个包含多个组的 DataFrameGroupBy 对象,我想制作一个具有多个功能(每组一个)的图形。我的研究表明,以下代码基本上应该产生一个多行的图形:

import pandas as pd
import matplotlib.pyplot as plt

with open("data.csv", encoding='utf-8') as datei:
    df = pd.read_csv(datei, sep=';')
    groups = df.groupby(['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
                         'L', 'M', 'N', 'O', 'P', 'Q'])  # Columns from A-Q are distinctive as a unit

    for element, group in groups:  # Looping over the GroupBy objects
        group.plot(x='R', y='X')  # Columns R and X contain the x- and y-axis values respectively

    # According to SO answers, calling .plot() should not create a graph until the graph itself is called
    plt.show()

相反,我得到了多个图表,每个图表都有一条线。按照一些说明,我尝试在我能想到的所有可能的地方推动plt.ion(),plt.ioff()plt.pause(0.5),但我不太明白它们是如何工作的,所以我可能没有正确完成。

标签: pythondataframematplotlibpandas-groupby

解决方案


您正在使用 pandas 的绘图功能。您可以通过使用 传递对轴的引用来指示此函数使用哪些轴ax=

import pandas as pd
import matplotlib.pyplot as plt

with open("data.csv", encoding='utf-8') as datei:
    df = pd.read_csv(datei, sep=';')
groups = df.groupby(['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
                     'L', 'M', 'N', 'O', 'P', 'Q'])  # Columns from A-Q are distinctive as a unit

fig, ax = plt.subplots()  # creates one figure with one axes
for element, group in groups:  # Looping over the GroupBy objects
    group.plot(x='R', y='X', ax=ax)  # Columns R and X contain the x- and y-axis values respectively

# According to SO answers, calling .plot() should not create a graph until the graph itself is called
plt.show()

推荐阅读