3

我有一个数据集,它有一个类别字段“城市”和 2 个指标,年龄和体重。我想使用循环为每个城市绘制散点图。但是,我正在努力将我需要的 group by 和 loop 组合在一个语句中。如果我只使用一个 for 循环,我最终会为每条记录生成一个图表,如果我按组进行分组,我会得到正确数量的图表但没有值。

这是我的代码,仅在我的组中使用了 for 循环,并被注释掉了:

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


d = {  'City': pd.Series(['London','New York', 'New York', 'London', 'Paris',
                        'Paris','New York', 'New York', 'London','Paris']),
       'Age' : pd.Series([36., 42., 6., 66., 38.,18.,22.,43.,34.,54]),
     'Weight': pd.Series([225,454,345,355,234,198,400, 256,323,310])
}

df = pd.DataFrame(d)

#for C in df.groupby('City'):
for C in df.City:
    fig = plt.figure(figsize=(5, 4))
    # Create an Axes object.
    ax = fig.add_subplot(1,1,1) # one row, one column, first plot
    # Plot the data.
    ax.scatter(df.Age,df.Weight, df.City == C, color="red", marker="^")
4

2 回答 2

2

不要plt.figure多次调用,因为每次调用都会创建一个新图形(粗略地说,窗口)。

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

d = {'City': ['London', 'New York', 'New York', 'London', 'Paris',
                        'Paris', 'New York', 'New York', 'London', 'Paris'],
     'Age': [36., 42., 6., 66., 38., 18., 22., 43., 34., 54],
     'Weight': [225, 454, 345, 355, 234, 198, 400, 256, 323, 310]}

df = pd.DataFrame(d)
fig, ax = plt.subplots(figsize=(5, 4))    # 1
df.groupby(['City']).plot(kind='scatter', x='Age', y='Weight', 
                          ax=ax,          # 2
                          color=['red', 'blue', 'green'])

plt.show()

在此处输入图像描述

  1. plt.subplots返回一个图形fig和一个坐标区ax
  2. 如果你传递ax=ax给 Panda 的 plot 方法,那么所有的图都将显示在同一轴上。

为每个城市制作一个单独的数字:

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

d = {'City': ['London', 'New York', 'New York', 'London', 'Paris',
                        'Paris', 'New York', 'New York', 'London', 'Paris'],
     'Age': [36., 42., 6., 66., 38., 18., 22., 43., 34., 54],
     'Weight': [225, 454, 345, 355, 234, 198, 400, 256, 323, 310]}

df = pd.DataFrame(d)
groups = df.groupby(['City'])
for city, grp in groups:                           # 1
    fig, ax = plt.subplots(figsize=(5, 4))
    grp.plot(kind='scatter', x='Age', y='Weight',  # 2
             ax=ax)               

    plt.show()
  1. 这也许就是你所缺少的。当您遍历 GroupBy 对象时,它会返回一个 2 元组:groupby 键和子 DataFrame。
  2. 使用grp, 子数据帧而不是df在 for 循环内。
于 2014-02-15T16:10:45.990 回答
2

我使用了另一篇文章中的 group by 并插入到我的代码中,通过以下方式为每个组生成图表:

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


d = {  'City': pd.Series(['London','New York', 'New York', 'London','Paris',
                        'Paris','New York', 'New York', 'London','Paris']),
       'Age' : pd.Series([36., 42., 6., 66., 38.,18.,22.,43.,34.,54]) ,
     'Weight': pd.Series([225,454,345,355,234,198,400, 256,323,310])

}

df = pd.DataFrame(d)

groups = df.groupby(['City'])
for city, grp in groups: 
    fig = plt.figure(figsize=(5, 4))
    # Create an Axes object.
    ax = fig.add_subplot(1,1,1) # one row, one column, first plot
    # Plot the data.
    ax.scatter(df.Age,df.Weight, df.City == city, color="red", marker="^")
于 2014-02-18T07:22:15.820 回答