Python:Matplotlib scatterplot对返回的句柄数有上限(不返回所有句柄以正确打印图例)

2024-10-04 03:24:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用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)

谢谢


Tags: fortitlematplotlibcountplushandlesfinalpoint
2条回答

如果将c设置为整数数组,则最多可以有15个图例条目

c = np.arange(len(15)) + 1

请注意,如果在此数组中传递除1到15以外的任何“外部”值,则不仅会忽略该值,而且图例最多只包含8个句柄和标签

可以使用长度大于15的数组,但每个值必须在[1..15]中,并且只有前15个值将被拾取以创建图例条目

假设您有29个数据点,我建议使用两个图例。每个图例都可以使用从1到15的颜色,并且每组都可以使用自己独特的标记

我尝试过其他颜色标签(供参考,https://matplotlib.org/3.1.0/gallery/color/named_colors.htmlhttps://matplotlib.org/3.1.0/tutorials/colors/colors.html?highlight=x11%20css4%20xkcd)。虽然这允许指定超过15种颜色,但在所有情况下,我都没有成功创建图例

注意: 我是python和matplotlib的新手。今天我自己在尝试标记18个数据点时第一次遇到了这个问题

为了UX/可读性,在一个绘图上有超过15个系列可能不明智

也许注释是在散点图上标记15个以上点的正确方法

如果知道数据集中标签的数量,可以通过显式地将num传递给legend_elements来绕过限制。这将强制提取正确数量的图例项

相关问题 更多 >