繁体   English   中英

Matplotlib 散点图 Plot 传奇创世之谜

[英]Matplotlib Scatter Plot Legend Creation Mystery

我有以下代码片段(c、s、x、y 的值是模型,但真实列表遵循相同的格式,只是大得多。只使用了两个 colors——尽管是红色和绿色。所有列表都是相同的尺寸)

问题是颜色图例未能实现。 我完全不知道为什么。 图例生成的代码片段基本上是来自文档的剪切粘贴,即( https://matplotlib.org/3.1.1/gallery/lines_bars_and_markers/scatter_with_legend.html#sphx-glr-gallery-lines-bars-and-标记散布图例 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()

Plot output:

在此处输入图像描述

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

就个人而言,我希望您的代码能够工作,也许值得在matplotlib 的 github将其作为错误或功能请求提出来。 编辑:实际上,已经在问题跟踪器上讨论了这个问题

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

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

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM