如何根据颜色添加图例?

时间:2021-06-23 04:54:27

标签: python-3.x matplotlib legend legend-properties

如何根据颜色添加图例?我查看了这个 question,但是我得到了一个关于句柄的错误。请问怎么了?

import matplotlib.pyplot as plt
import pandas as pd

fig, ax = plt.subplots(figsize = (10,5))

colors = {'F16':'tab:blue', 'F898':'tab:orange'}

rv_times = [4,4,5,5]
rv_rvs = [4,5,5,7]
rv_sigma = [0.1, 0.1, 0.2, 0.02]
rv_telescopes = ['F16', 'F898', 'F16', 'F898']

d = {'rv_times': rv_times, 'rv_rvs': rv_rvs, 'rv_sigma': rv_sigma, 'rv_telescopes': rv_telescopes }
df = pd.DataFrame(data=d)

ax.errorbar(rv_times, rv_rvs, rv_sigma, color = 'maroon', marker = 'o', fmt='o', zorder = -1)
ax.scatter(df['rv_times'], df['rv_rvs'], color = df['rv_telescopes'].map(colors), marker = 'o', s=20, zorder = 1)

#ax.legend(title='rv_telescopes', handles=handles, bbox_to_anchor=(1.05, 1), loc='upper left')
# --> NameError: name 'handles' is not defined

plt.tight_layout()
plt.show()

0 个答案:

没有答案