[英]Python: Matplotlib scatterplot has an upper limit on the number of handles returned (not returning all handles to properly print legend)
我正在使用 matplotlib 制作散点图。 我的数据有我正在绘制的点的 x 和 y 坐标,以及一个取值从 1 到 29 的“计数”值。为了表示图例中的“计数”,我使用了 3 种不同的方式给定以下。
a) 散点大小
b) 散点颜色
c) 替代“计数”上的 X 标记
由于有 29 个计数,我预计图例中有 29 个条目。 但是,图例条目的数量似乎有 8 个上限。有没有办法确保我可以显示所有 29 个图例条目。 我到目前为止的代码如下
point = cluster_actual_crashes
# point.geometry gives x and y coordinates
# point['count'] gives the count value for that data point
scatter = plt.scatter(point.geometry.x, point.geometry.y,
edgecolors = 'black',
linewidths = 2,
c=point['count'],
s=100*point['count'].values^2,
cmap = 'hsv',#Cyclic colormapshttps://matplotlib.org/3.1.0/tutorials/colors/colormaps.html
alpha = 0.5)
# point_plus are the points which are marked with 'X'
point_plus = point[point['count'].isin(point['count'].value_counts().index[::2])]
scatter_plus = plt.scatter(point_plus.geometry.x, point_plus.geometry.y,
marker = "x",
s=80*point_plus['count'].values^2 )
# https://matplotlib.org/3.1.1/tutorials/intermediate/legend_guide.html
handles, labels = scatter.legend_elements(prop='sizes')
handles2, _ = scatter.legend_elements(prop='colors')
handles_plus, _ = scatter_plus.legend_elements(prop='sizes')
handles_final = []
for i, handle in enumerate(handles):
handles[i].set_c(handles2[i].get_c())
handles[i].set_linewidth(2)
handles[i].set_markeredgecolor('black')
if ((i+1)%2 == 1):
# print(int((i-1)/2))
handles_final.append((handles[i],handles2[i], handles_plus[int((i-1)/2)]))
else:
handles_final.append((handles[i],handles2[i]))
# handles[i].set_markeredgecolor('red')
labels = [str(i) for i in set(point['count'].values)]
# Add a title to legend with title keyword
plt.legend(handles_final, labels, title='Number of Crashes',
loc='upper left', bbox_to_anchor=(1.04, 0.25, 0.5, 0.5),
labelspacing=2,
borderpad=1.5,
title_fontsize=titlefontsize*0.9,
fontsize = titlefontsize*0.9)
谢谢,
如果 c 设置为整数数组,则最多可以有 15 个图例条目。
c = np.arange(len(15)) + 1
请注意,如果您在此数组中传递除 1 到 15 之外的任何“外来”值,则不仅会忽略该值,而且图例最多仅包含 8 个句柄和标签。
您可以拥有一个长度大于 15 的数组,但每个值都必须在 [1..15] 中,并且只会选取前 15 个值来创建图例条目。
鉴于您有 29 个数据点,我建议使用两个图例。 每个图例可以使用从 1 到 15 运行的 colors,并且每组都可以使用自己独特的标记。
I have tried other color labels (for reference, https://matplotlib.org/3.1.0/gallery/color/named_colors.html and https://matplotlib.org/3.1.0/tutorials/colors/colors.html?高亮=x11%20css4%20xkcd )。 虽然这允许超过 15 个 colors 的规范,但在所有情况下,我都未能成功创建图例。
注意:我是 python 和 matplotlib 的新手。 我今天在尝试 label 18 个数据点时第一次遇到这个问题。
对于 UX/可读性,在单个 plot 上拥有超过 15 个系列可能是不明智的?
也许注释是 label 在散点图上超过 15 个点的正确方法?
如果您知道数据集中的标签数量,则可以通过将num
显式传递给legend_elements
来绕过限制。 这将强制提取正确数量的图例项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.