我有一个pandas数据帧。前两列是x,y轴值,第三列是'label1',第四列是'label2'。 如果'label1'== 0,用markerfacecolor ='red'绘制点;否则如果'label1'== 0,用markerfacecolor ='blue'绘制点; 如果'label2'== 0,用marker ='。'绘制点。否则如果'label1'== 0,用marker ='x'绘制点; 如何在同一散点图中使用数据框绘制这四种类型的点? 非常感谢!
答案 0 :(得分: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')
答案 1 :(得分:0)
用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()