在matplotlib图例中标记特定的散点

时间:2019-11-25 17:54:37

标签: python matplotlib

我需要在此图的图例中添加“ blue scat”,而无需重写图创建的所有基础。通过直接通过patches[0]patches[1]标记艺术家,我可以在图例中没有四个条目的情况下指定“红色条”和“蓝色条”,但是我找不到解决方法与散点图相同。 legend_elements()听起来很有前途,但我无法从中得到任何有用的帮助。 sample chart

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.axes import Axes as ax

df = pd.DataFrame({'barVals':[5, 10, 15, 20], 'scatVals':[7, 12, 17, 22], 'color':['red', 'blue', 'red', 'blue']})
df

bar = plt.bar(range(len(df)), df['barVals'], color=df['color'], alpha=0.7)
sc = plt.scatter(range(len(df)), df['scatVals'], s=20, c=df['color'])

plt.legend((bar.patches[0], bar.patches[1], sc), ('red bar', 'blue bar', 'red scat', 'blue scat'), scatterpoints=1)

plt.show()

1 个答案:

答案 0 :(得分:0)

您可以使用代理艺术家来创建图例。

import pandas as pd
import matplotlib.pyplot as plt


df = pd.DataFrame({'barVals':[5, 10, 15, 20], 'scatVals':[7, 12, 17, 22], 'color':['red', 'blue', 'red', 'blue']})

bar = plt.bar(range(len(df)), df['barVals'], color=df['color'], alpha=0.7)
sc = plt.scatter(range(len(df)), df['scatVals'], s=20, c=df['color'])

proxys = [plt.Line2D([],[], marker="o", ms=5, ls="", color=c) for c in ['red', 'blue']]
plt.legend((bar.patches[0], bar.patches[1], *proxys), ('red bar', 'blue bar', 'red scat', 'blue scat'), scatterpoints=1)

plt.show()

enter image description here

相关问题