matplotlib 如何将图例添加到按文本颜色编码的散点图中

xzlaal3s  于 2023-05-18  发布在  其他
关注(0)|答案(3)|浏览(153)

我试图根据列中的字符串对散点图进行颜色编码。我不知道该怎么设置传奇。

可重复示例

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

电流输出

期望输出

与上面的图相同,我只想定义图例句柄。

62o28rlo

62o28rlo1#

可以使用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})

你会得到

w6mmgewl

w6mmgewl2#

您将创建一个图例手柄列表,如下所示。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()
du7egjpx

du7egjpx3#

您是否对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()

输出:

相关问题