matplotlib 散点图图例不依赖于点的颜色

问题描述 投票:0回答:1

我想让散点图的图例不依赖于点的颜色。简单的例子如下:

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

fake_data = np.array([[1,1],[1,2],[1,3],[2,1],[2,2],[2,3],[3,1],[3,2],[3,3]])
fake_df = pd.DataFrame(fake_data, columns=['X', 'Y'])
groups = np.array(['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C'])
fake_df['Group'] = groups
names = np.array(['bla', 'blu', 'ble', 'blam', 'blom', 'bluh', 'bom', 'bam', 'bem'])
fake_df['names'] = names

group_codes = {k:idx for idx, k in enumerate(fake_df.Group.unique())}
fake_df['colors'] = fake_df['Group'].apply(lambda x: group_codes[x])
fig, ax = plt.subplots(figsize=(5,5))
scatter = ax.scatter(fake_data[:,0], fake_data[:,1], c=fake_df['colors'])
for num, names in enumerate(fake_data):
    plt.text(fake_data[num,0], fake_data[num, 1], num)
handles = scatter.legend_elements(num=[0,1,2,3])[0] 
ax.legend(title='Group\nCodes', handles=handles,  labels=group_codes.keys(), bbox_to_anchor=(1, 0.5), loc="upper left")
plt.show()

我想保存颜色,因为我在那里进行了聚类分析,但我想要一个看起来像这样的图例:

1 - 'bla'
2 - 'blu'
3 - 'ble' and so on. 

当前剧情:

current plot 数据框看起来像:

   X  Y Group names  colors
0  1  1     A   bla       0
1  1  2     A   blu       0
2  1  3     A   ble       0
3  2  1     B  blam       1
4  2  2     B  blom       1
5  2  3     B  bluh       1
6  3  1     C   bom       2
7  3  2     C   bam       2
8  3  3     C   bem       2

我只对点进行了不太有用的计数,但我想将数字与相应的名称连接起来,这将显示在图例中。

python matplotlib legend
1个回答
0
投票
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

fake_data = np.array([[1, 1], [1, 2], [1, 3], [2, 1], [2, 2], [2, 3], [3, 1], [3, 2], [3, 3]])
fake_df = pd.DataFrame(fake_data, columns=['X', 'Y'])
groups = np.array(['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C'])
fake_df['Group'] = groups
names = np.array(['bla', 'blu', 'ble', 'blam', 'blom', 'bluh', 'bom', 'bam', 'bem'])
fake_df['names'] = names

group_codes = {k: idx for idx, k in enumerate(fake_df.Group.unique())}
fake_df['colors'] = fake_df['Group'].apply(lambda x: group_codes[x])

fig, ax = plt.subplots(figsize=(5, 5))
scatter = ax.scatter(fake_data[:, 0], fake_data[:, 1], c=fake_df['colors'])
for num, name in enumerate(names):
    plt.text(fake_data[num, 0], fake_data[num, 1], num + 1)

handles = scatter.legend_elements(num=[0, 1, 2, 3])[0]
labels = [f"{num + 1} - '{name}'" for num, name in enumerate(names)]
ax.legend(title='Legend', handles=handles, labels=labels, bbox_to_anchor=(1, 0.5), loc="upper left")
plt.show()

© www.soinside.com 2019 - 2024. All rights reserved.