簡體   English   中英

如何使用兩列信息在同一散點圖中繪制四種不同類型的點?

[英]How to draw four different types of points in the same scatter plot using two columns' info?

我有一個熊貓數據框。 前兩列是x,y軸值,第三列是“ label1”,第四列是“ label2”。 如果'label1'== 0,則用markerfacecolor ='red'繪制點; 否則,如果'label1'== 0,則用markerfacecolor ='blue'繪制點; 如果'label2'== 0,則用marker ='繪制點。 否則,如果'label1'== 0,則用marker ='x'繪制點; 如何在同一散點圖中使用數據框繪制這四種類型的點? 非常感謝!

您可以在同一軸上繪制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')

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM