【问题标题】:How to draw four different types of points in the same scatter plot using two columns' info?如何使用两列的信息在同一个散点图中绘制四种不同类型的点?
【发布时间】:2015-09-01 14:24:07
【问题描述】:

我有一个熊猫数据框。前两列是 x,y 轴值,第三列是“label1”,第四列是“label2”。 如果'label1'==0,用markerfacecolor='red'绘制点;否则如果'label1'==0,用markerfacecolor='blue'绘制点; 如果'label2'==0,用marker='.'绘制点;否则如果'label1'==0,用marker='x'绘制点; 如何在同一个散点图中使用数据框绘制这四种类型的点? 非常感谢!

【问题讨论】:

  • 如果我的方法可以帮助您解决问题,您能接受我的回答吗?非常感谢。

标签: python matplotlib


【解决方案1】:

您可以为同一轴上的 4 个子组绘制散点图。代码如下:

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

# x, y
xy = np.random.randn(100, 2)
# label1, label2
labels = np.random.choice([True, False], size=(100, 2)).astype(int)
# construct data
data = np.concatenate([xy, labels], axis=1)
df = pd.DataFrame(data, columns=['x', 'y', 'label1', 'label2'])
# group into 4 sub-groups according to labels
mask1 = (df.label1 == 1) & (df.label2 == 0)
mask2 = (df.label1 == 0) & (df.label2 == 0)
mask3 = (df.label1 == 1) & (df.label2 == 1)
mask4 = (df.label1 == 0) & (df.label2 == 1)
# do scatter plots for 4 sub-groups individually on the same axes, add label info
fig, ax = plt.subplots(figsize=(12, 8))
ax.scatter(df.x[mask1], df.y[mask1], marker='o', c='r', label='label1 == 1, label2 == 0')
ax.scatter(df.x[mask2], df.y[mask2], marker='x', c='b', label='label1 == 0, label2 == 0')
ax.scatter(df.x[mask3], df.y[mask3], marker='.', c='g', label='label1 == 1, label2 == 1' )
ax.scatter(df.x[mask4], df.y[mask4], marker='<', c='k', label='label1 == 0, label2 == 1')
# show the legend
ax.legend(loc='best')

【讨论】:

    【解决方案2】:

    用 4 种颜色绘制的一种方法是:

    import numpy as np
    import matplotlib.pyplot as plt
    
    
    N = 50
    x = np.random.rand(N)
    y = np.random.rand(N)
    colors = np.random.randint(4,size=N)
    area = np.pi * (15 * np.random.rand(N))**2 # 0 to 15 point radiuses
    
    plt.scatter(x, y, s=area, c=colors, alpha=0.5)
    plt.show()
    

    【讨论】:

    • 感谢您的回复。是否可以使用两种类型的标记和两种颜色而不是两种颜色?再次感谢!
    猜你喜欢
    • 1970-01-01
    • 2019-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-05
    • 1970-01-01
    • 2022-12-04
    • 1970-01-01
    相关资源
    最近更新 更多