[英]Plot colormap to unique labels - Matplotlib
我希望 map 將顏色變為由相關 label 確定的箭筒 plot。 使用下面,唯一項目由 col Label
定義。 我希望 plot 中的每個獨特項目的顏色相同Label
。
注意:獨特項目的數量可能因 df 而異,所以我不想硬編碼 colors。 我希望采用任意數量的獨特標簽並傳遞顏色圖。
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import random
import seaborn as sns
df = pd.DataFrame(np.random.randint(0,20,size=(100, 4)), columns=list('XYUV'))
labels = df['X'].apply(lambda x: random.choice(['A', 'B', 'C', 'D']))
df['Label'] = labels
X = df['X']
Y = df['Y']
U = df['U']
V = df['V']
fig,ax = plt.subplots()
ax.set_xlim(-10, 30)
ax.set_ylim(-10, 30)
color_labels = df['Label'].unique()
col_values = sns.color_palette('Set2')
color_map = dict(zip(color_labels, col_values))
ax.quiver(X, Y, (U-X), (V-Y), angles = 'xy', scale_units = 'xy', scale = 1, color = color_map)
您可以為每個向量創建一個 colors 列表
colors = [color_map[label] for label in df['Label'].values]
使用colors
,
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import random
import seaborn as sns
import matplotlib.patches as mpatches
data = np.vstack((np.random.randint(0,10,size=(25, 4)),
np.random.randint(10,20,size=(25, 4)),
np.random.randint(20,30,size=(25, 4)),
np.random.randint(30,40,size=(25, 4))))
df = pd.DataFrame(data, columns=list('XYUV'))
df['Label'] = np.repeat(np.array(['A','B','C','D'])[:,None],25)
X = df['X']
Y = df['Y']
U = df['U']
V = df['V']
fig,ax = plt.subplots()
ax.set_xlim(-10, 40)
ax.set_ylim(-10, 40)
color_labels = df['Label'].unique()
col_values = sns.color_palette('Set2')
color_map = dict(zip(color_labels, col_values))
colors = [color_map[label] for label in df['Label'].values]
ax.quiver(X, Y, (U-X), (V-Y), angles = 'xy', scale_units = 'xy', scale = 1, color = colors,)
ax.legend(handles=[mpatches.Patch(color=v,label=k) for k,v in color_map.items()])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.