【问题标题】:Scatter plots in Pandas/Pyplot: How to plot by category with different markersPandas/Pyplot 中的散点图:如何使用不同的标记按类别绘制
【发布时间】:2014-12-30 19:06:37
【问题描述】:

基于之前的问题:Scatter plots in Pandas/Pyplot: How to plot by category

下面的代码是该帖子的解决方案,并将每个组绘制为不同的颜色。如何将每个组绘制为不同的标记?

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()

【问题讨论】:

    标签: python matplotlib pandas


    【解决方案1】:

    在迭代组时,您可以使用 zip 迭代标记列表。下面的代码将遍历markers 列表并依次使用ax.plot 行中的marker=marker 分配每个元素。

    我还添加了itertools.cycle,这将导致迭代在到达终点后重新开始,这意味着如果您有超过 3 个组,则它不会失败。例如,如果您有 4 个组,那么标记将是 'x', 'o', '^', 'x'

    import matplotlib.pyplot as plt
    import numpy as np
    import pandas as pd
    np.random.seed(1974)
    
    from itertools import cycle
    
    # 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')
    
    markers = ['x', 'o', '^']
    
    # Plot
    fig, ax = plt.subplots()
    ax.margins(0.05) # Optional, just adds 5% padding to the autoscaling
    for (name, group), marker in zip(groups, cycle(markers)):
        ax.plot(group.x, group.y, marker=marker, linestyle='', ms=12, label=name)
    ax.legend()
    
    plt.show()
    

    【讨论】:

    猜你喜欢
    • 2014-03-06
    • 2021-01-31
    • 2013-01-27
    • 2020-11-03
    • 1970-01-01
    • 2021-11-06
    • 1970-01-01
    相关资源
    最近更新 更多