【问题标题】:Matplotlib Scatter Plot Legend Creation MysteryMatplotlib 散点图传奇创造之谜
【发布时间】:2020-09-16 07:44:06
【问题描述】:

我有以下代码片段(c、s、x、y 的值是模型,但真正的列表遵循相同的格式,只是更大。只使用了两种颜色 - 红色和绿色。所有列表都是大小相同)

问题是颜色图例未能实现。我完全不知道为什么。图例生成的代码 sn-ps 基本上是从文档中剪切粘贴,即 (https://matplotlib.org/3.1.1/gallery/lines_bars_and_markers/scatter_with_legend.html#sphx-glr-gallery-lines-bars-and-markers-scatter-with-legend-py)

有人知道吗?

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

c = [ 'g', 'r', 'r', 'g', 'g', 'r', 'r', 'r', 'g', 'r']
s = [ 10, 20, 10, 40, 60, 90, 90, 50, 60, 40]
x = [ 2.4, 3.0, 3.5, 3.5, 3.5, 3.5, 3.5, 2.4, 3.5, 3.5]
y = [24.0, 26.0, 20.0, 19.0, 19.0, 21.0, 20.0, 23.0, 20.0, 20.0]

fig, ax = plt.subplots()

scatter = plt.scatter(x, y, s=s, c=c, alpha=0.5)

# produce a legend with the unique colors from the scatter
handles, lables = scatter.legend_elements()
legend1 = ax.legend(handles, labels, loc="lower left", title="Colors")
ax.add_artist(legend1)

# produce a legend with a cross section of sizes from the scatter
handles, labels = scatter.legend_elements(prop="sizes", alpha=0.5)
legend2 = ax.legend(handles, labels, loc="upper right", ncol=2, title="Sizes")

plt.show()

绘图输出:

【问题讨论】:

  • 你试过像legend1 = ax.legend(*scatter.legend_elements(), loc="lower left", title="Colors")这样的实际代码
  • @Sheldore 尝试了相同的结果。请参阅下面发布的解决方法。谢谢。

标签: python matplotlib colors legend legend-properties


【解决方案1】:

似乎legend_elements() 仅在传递给c= 以映射到颜色图的数字数组时使用。 您可以通过将代码中的c=c 替换为c=s 来进行测试,您将获得所需的输出。

就个人而言,我希望您的代码能够正常工作,也许值得将其作为错误或功能请求在matplotlib's github 提出。 编辑:实际上,已经有关于这个问题的讨论on the issue tracker

绕过此限制的一种方法是将您的颜色名称数组替换为数字数组,并创建一个自定义颜色图,将数组中的每个值映射到所需的颜色:

#c = [ 'g', 'r', 'r', 'g', 'g', 'r', 'r', 'r', 'g', 'r']
c = [0, 1, 1, 0, 0, 1, 1, 1, 0, 1]
cmap = matplotlib.colors.ListedColormap(['g','r'])
s = [ 10, 20, 10, 40, 60, 90, 90, 50, 60, 40]
x = [ 2.4, 3.0, 3.5, 3.5, 3.5, 3.5, 3.5, 2.4, 3.5, 3.5]
y = [24.0, 26.0, 20.0, 19.0, 19.0, 21.0, 20.0, 23.0, 20.0, 20.0]

fig, ax = plt.subplots()

scatter = plt.scatter(x, y, s=s, c=c, alpha=0.5, cmap=cmap)

# produce a legend with the unique colors from the scatter
handles, labels = scatter.legend_elements()
legend1 = ax.legend(handles, labels, loc="lower left", title="Colors")
ax.add_artist(legend1)

# produce a legend with a cross section of sizes from the scatter
handles, labels = scatter.legend_elements(prop="sizes", alpha=0.5)
legend2 = ax.legend(handles, labels, loc="upper right", ncol=2, title="Sizes")

plt.show()

【讨论】:

  • 谢谢!我正在研究自定义颜色图作为一个选项,所以这对我来说非常有意义。阅读问题跟踪线程......不要认为它会在可预见的将来被更改/修复。我会在那里保留判断力。再次感谢您!
猜你喜欢
  • 2020-07-22
  • 1970-01-01
  • 1970-01-01
  • 2013-06-29
  • 2017-06-22
  • 2021-11-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多