Python Matplotlib散点图传奇创作之谜

Python Matplotlib散点图传奇创作之谜,python,matplotlib,colors,legend,legend-properties,Python,Matplotlib,Colors,Legend,Legend Properties,我有以下截取的c、s、x、y的代码值是实体模型,但真正的列表遵循相同的格式,只是要大得多。只使用了两种颜色——红色和绿色。所有列表的大小都相同 问题是颜色图例未能实现。我完全不知道为什么。图例生成的代码段基本上是从文档中剪切粘贴的,即 有人知道吗 import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib inline c = [ 'g', 'r', 'r', 'g', 'g', 'r',

我有以下截取的c、s、x、y的代码值是实体模型,但真正的列表遵循相同的格式,只是要大得多。只使用了两种颜色——红色和绿色。所有列表的大小都相同

问题是颜色图例未能实现。我完全不知道为什么。图例生成的代码段基本上是从文档中剪切粘贴的,即

有人知道吗

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()
绘图输出:

legend_元素似乎只在c=被传递一个数字数组以映射到colormap时使用。 您可以通过在代码中用c=s替换c=c进行测试,您将获得所需的输出

就我个人而言,我希望您的代码能够正常工作,也许值得将其作为一个bug或是一个功能请求提出来。编辑:事实上,已经有关于这个问题的讨论了

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

#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()

您是否尝试过实际的代码,如legend1=ax.legend*scatter.legend\u元素,loc=左下角,title=Colors@Sheldore以同样的结果尝试。请参阅下面发布的解决方法。谢谢,谢谢!我把定制颜色映射作为一种选择,所以它对我来说非常有意义。阅读问题跟踪线程…不要认为它在可预见的将来会被更改/修复。我将在那里保留判断。再次感谢你!