python - matplotlib 为单个散点图添加具有多个条目的图例

我正在为如下所示的数据集绘制散点图:

x = [1, 1, 2, 2, 3, 3, 4, 4]
y = [1, 2, 3, 4, 1, 2, 3, 4]
labels = [1, 3, 0, 2, 2, 1, 0, 3]

colors = np.array(plt.rcParams['axes.prop_cycle'].by_key()['color'])

plt.scatter(x, y, color=colors[labels])

如果我调用 plt.legend,对于整个数据集,将只显示一个条目,带有第一个符号。如何创建一个包含所有四个元素的图例,并显示为好像我绘制了四个单独的数据集?

可能相关:Matplotlib histogram with multiple legend entries
基于:Matplotlib, how to loop?

最佳答案

我认为总体上最简单的解决方案是将所有工作委托(delegate)给 matplotlib。此处描述了该方法:https://matplotlib.org/gallery/lines_bars_and_markers/scatter_with_legend.html#automated-legend-creation .对于这种简化的方法,使用 PathCollection's legend_elements方法就是您所需要的:

s = plt.scatter(x, y, c=labels)
plt.legend(*s.legend_elements())

更改颜色图或用其他内容(例如文本)替换标签是微不足道的:

text_labels = ['one', 'two', 'three', 'four']
s = plt.scatter(x, y, c=labels, cmap='jet', vmin=0, vmax=4)
plt.legend(s.legend_elements()[0], text_labels)

如果 labels 还不是 [0-n) 范围内元素的排序数组,可以使用 np.unique 轻松获得它:

labels = ['b', 'd', 'a', 'c', 'c', 'b', 'a', 'd']
text_labels, labels = np.unique(labels, return_inverse=True)

https://stackoverflow.com/questions/61905622/

相关文章:

javascript - 谷歌邮箱 : Button/Link which trigger a sc

python - 我怎样才能看到 Pandas 的几个最大值?

amazon-web-services - CognitoIdentityCredentials 不

python - 类型错误 : get_bind() got an unexpected keywo

asp.net-core - 脚手架MVC在继承IdentityDbContext时不加载Appli

swiftui - 如何获得 Swift UI 的水平选择器?

python - 在对数刻度上生成均匀间隔的值(如 `np.linspace()` ,但在对数刻度上

scala - 为什么在使用 List 时得到的结果与使用 Tuple 时得到的结果不同?

java - OPTIONS、TRACE 和 HEAD 请求方法的用例

javascript - onChange 在每次击键时触发