Pandas/Pyplot中的散点图:如何按类别绘制

发布于 2021-02-02 23:17:13

我正在尝试使用Pandas DataFrame对象在pyplot中制作一个简单的散点图,但是想要一种有效的方式来绘制两个变量,但要用第三列(键)来指定符号。我已经尝试过使用df.groupby的各种方法,但是没有成功。下面是一个示例df脚本。这会根据“ key1”为标记着色,但是我想看到带有“ key1”类别的图例。我靠近吗?谢谢。

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame(np.random.normal(10,1,30).reshape(10,3), index = pd.date_range('2010-01-01', freq = 'M', periods = 10), columns = ('one', 'two', 'three'))
df['key1'] = (4,4,4,6,6,6,8,8,8,8)
fig1 = plt.figure(1)
ax1 = fig1.add_subplot(111)
ax1.scatter(df['one'], df['two'], marker = 'o', c = df['key1'], alpha = 0.8)
plt.show()
关注者
0
被浏览
65
1 个回答
  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

    你可以使用scatter它,但是这需要为你提供数值key1,并且你不会注意到图例。

    最好只plot对像这样的离散类别使用。例如:

    import matplotlib.pyplot as plt
    import numpy as np
    import pandas as pd
    np.random.seed(1974)
    
    # Generate Data
    num = 20
    x, y = np.random.random((2, num))
    labels = np.random.choice(['a', 'b', 'c'], num)
    df = pd.DataFrame(dict(x=x, y=y, label=labels))
    
    groups = df.groupby('label')
    
    # Plot
    fig, ax = plt.subplots()
    ax.margins(0.05) # Optional, just adds 5% padding to the autoscaling
    for name, group in groups:
        ax.plot(group.x, group.y, marker='o', linestyle='', ms=12, label=name)
    ax.legend()
    
    plt.show()
    

    如果你希望外观看起来像默认pandas样式,则只需rcParams使用pandas样式表进行更新,并使用其颜色生成器即可。(我也略微调整了图例):

    import matplotlib.pyplot as plt
    import numpy as np
    import pandas as pd
    np.random.seed(1974)
    
    # Generate Data
    num = 20
    x, y = np.random.random((2, num))
    labels = np.random.choice(['a', 'b', 'c'], num)
    df = pd.DataFrame(dict(x=x, y=y, label=labels))
    
    groups = df.groupby('label')
    
    # Plot
    plt.rcParams.update(pd.tools.plotting.mpl_stylesheet)
    colors = pd.tools.plotting._get_standard_colors(len(groups), color_type='random')
    
    fig, ax = plt.subplots()
    ax.set_color_cycle(colors)
    ax.margins(0.05)
    for name, group in groups:
        ax.plot(group.x, group.y, marker='o', linestyle='', ms=12, label=name)
    ax.legend(numpoints=1, loc='upper left')
    
    plt.show()
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看