1

我正在尝试根据列中的字符串对散点图进行颜色编码。我不知道如何设置图例。

可重复的示例

%matplotlib inline
import matplotlib.pyplot as plt
import pandas as pd

## Dummy Data
x = [0, 0.03, 0.075, 0.108, 0.16, 0.26, 0.37, 0.49, 0.76, 1.05, 1.64,
    0.015, 0.04, 0.085, 0.11, 0.165, 0.29, 0.37, 0.6, 0.78, 1.1]
y = [16.13, 0.62, 2.15, 41.083, 59.97, 13.30, 7.36, 6.80, 4.97, 3.53, 11.77,
    30.21, 64.47, 57.64, 56.83, 46.69, 4.22, 30.35, 35.12, 5.22, 25.32]
label = ['a', 'a', 'c', 'a', 'c', 'b', 'c', 'c', 'c', 'b', 'c',
        'c', 'c', 'a', 'b', 'a', 'a', 'a', 'b', 'c', 'c', 'c']

df = pd.DataFrame(
    list(zip(x, y, label)), 
    columns =['x', 'y', 'label']
    ) 

## Set up colors dictionary
mydict = {'a': 'darkviolet',
          'b': 'darkgoldenrod',
          'c': 'olive'}

## Plotting
plt.scatter(df.x, df.y, c=df['label'].map(mydict))
plt.legend(loc="upper right", frameon=True)

当前输出 期望输出 与上图相同,我只想定义图例句柄。在此处输入图像描述

谢谢你的帮助

4

3 回答 3

3

您可以使用matplotlib.patches.mpatches

只需将这些代码行添加到您的脚本中

import matplotlib.patches as mpatches

fake_handles = [mpatches.Patch(color=item) for item in mydict.values()]
label = mydict.keys()
plt.legend(fake_handles, label, loc='upper right', prop={'size': 10})

你会得到

数字

于 2020-10-16T01:16:55.743 回答
1

您是否愿意seaborn

import seaborn as sns
sns.scatterplot(data=df, x='x',y='y',hue='label', palette=mydict)

输出:

在此处输入图像描述

仅使用 pandas/matplotlib,您可以执行循环:

fig, ax = plt.subplots()
for l,d in df.groupby('label'):
    d.plot.scatter(x='x',y='y', label=l, c=mydict[l], ax=ax)

plt.legend()

输出:

在此处输入图像描述

于 2020-10-16T01:07:46.047 回答
0

在此处输入图像描述

您将制作一个图例句柄列表,如下所示。legendhandle将采用行列表的第一个元素。

import matplotlib.pyplot as plt
import pandas as pd

## Dummy Data
x = [0, 0.03, 0.075, 0.108, 0.16, 0.26, 0.37, 0.49, 0.76, 1.05, 1.64,
    0.015, 0.04, 0.085, 0.11, 0.165, 0.29, 0.37, 0.6, 0.78, 1.1]
y = [16.13, 0.62, 2.15, 41.083, 59.97, 13.30, 7.36, 6.80, 4.97, 3.53, 11.77,
    30.21, 64.47, 57.64, 56.83, 46.69, 4.22, 30.35, 35.12, 5.22, 25.32]
label = ['a', 'a', 'c', 'a', 'c', 'b', 'c', 'c', 'c', 'b', 'c',
        'c', 'c', 'a', 'b', 'a', 'a', 'a', 'b', 'c', 'c', 'c']

df = pd.DataFrame(
    list(zip(x, y, label)), 
    columns =['x', 'y', 'label']
    ) 

## Set up colors dictionary
mydict = {'a': 'darkviolet',
          'b': 'darkgoldenrod',
          'c': 'olive'}
legendhandle = [plt.plot([], marker="o", ls="", color=color)[0] for color in list(mydict.values())]
plt.scatter(df.x, df.y, c=df['label'].map(mydict))
plt.legend(legendhandle,list(mydict.keys()),loc="upper right", frameon=True)
plt.show()
于 2020-10-16T01:19:46.813 回答