matplotlib 将色彩Map图打印到唯一标签

gt0wga4j  于 2023-05-23  发布在  其他
关注(0)|答案(1)|浏览(175)

我希望将不同的颜色Map到由相关标签确定的 Flutter 图。使用下面的方法,唯一项由col Label定义。我希望为Label中的每个唯一项目绘制相同的颜色。
注意:独特的项目的数量可能会有所不同,所以我不想硬编码的颜色。我希望采取任何数量的独特的标签,并通过一个色彩Map表。

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

xxb16uws1#

您可以为每个矢量创建一个颜色列表

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

相关问题