如何在matplotlib点大小图例中指定点的大小

时间:2020-04-02 01:33:22

标签: python matplotlib

我的目标是(尽可能优雅地)制作一个散点图的图例,以显示散点点大小的最小值,中点和最大值。

我正在尝试使用legend_elements函数。我已经浏览了demo和文档,但似乎无法找到一种使用该功能来完成我想要的方法的方法。

接下来,我尝试召集与我相同的分数。原因是我可以选择第一个,中间和最后一点来近似最小值,均值和最大值。但是,图例显示的最小和最大点不是数据中的最小和最大点。为什么召集与采样点数量相同的点图例不产生最小值和最大值?是否可以使用legend_elements之类的辅助函数来构造图例,以在散点图中显示最小,中等和最大点的大小?

import matplotlib.pyplot as plt
import numpy as np

# ensure repeatability
np.random.seed(123456)

NSAMPS = 100 # Number of scattered points

idx = [0, NSAMPS // 2, -1] # min-medium-max coordinates

# randomly sample x, y, and size from 0 to 100
RandomMatrix = 100 * np.random.random((NSAMPS, 3))

# make scatter plot
sc = plt.scatter(RandomMatrix[:, 0], RandomMatrix[:, 1], s=RandomMatrix[:, 2])

# recover the same number of element sizes
sizes = sc.legend_elements("sizes", num=NSAMPS)

# parse the sizes for the first, middle, and last entries
args = (list(np.array(sizes[0])[idx]), list(np.array(sizes[1])[idx])) 

# show that the estimated min and max sizes are 1.6 and 98.4, respectively
plt.legend(*args, **{'title': "I want the true min-med-max here! [thanks for taking a look:)]", 'bbox_to_anchor': (1, 1)})

# save figure
plt.savefig('mybigprobelem')

# show that the true minimum and maximum sizes are 1.06 and 98.9
# (I wish for these numbers/sizes to be in the first and third legend positions)
print('True min-max: ', RandomMatrix[:, 2].min(), RandomMatrix[:, 2].max())

enter image description here

True min-max:  1.0692999366311629 98.89493616046823

1 个答案:

答案 0 :(得分:2)

args替换为:

args = (list(np.array(sizes[0])[idx]), np.sort(RandomMatrix[:,2])[idx]) 

输出:

enter image description here

相关问题