python - 如何更改图例中散点标记的大小?

标签 python matplotlib graph legend scatter

我基本上是用 matplotlib 绘制散点图,但是,我用半径改变了每个点。

当我使用 plt.legend() 显示我的图例时,它看起来像这样...... enter image description here

是否有缩小圆的命令。我知道这可能是一个非常微不足道的问题,我已经尝试搜索它了!

最佳答案

解决方案可能取决于图例中的标记是否应与原始大小相比进行缩放,或者是否需要独立于原始大小的恒定标记大小。

A.缩放标记

您可以使用legend.markerscale rcParam .

plt.rcParams["legend.markerscale"] = 0.3

或图例的 markerscale 参数。

plt.legend(markerscale=0.3)

来自legend documentation :

markerscale : None or int or float

The relative size of legend markers compared with the originally drawn ones. Default is None which will take the value from the legend.markerscale rcParam.

例子:

import matplotlib.pyplot as plt
plt.rcParams["legend.markerscale"] = 0.3

plt.scatter([.3,.5], [.3,.6], s=1000, label="label")
plt.scatter([.7,.4], [.3,.6], s=81, marker="^", label="label2")
plt.legend()
plt.show()

enter image description here

请注意,这将同时缩放所有标记。

B.设置恒定的标记大小

如果您希望图例中的标记大小与散点的实际大小无关,则解决方案会稍微复杂一些。您可以使用图例的 handler_map 将所需的标记大小设置为图例句柄。

import matplotlib.pyplot as plt
from matplotlib.legend_handler import HandlerPathCollection

sc = plt.scatter([.3,.5], [.3,.6], s=1000, label="label")
plt.scatter([.7,.4], [.3,.6], s=[100,300], marker="^", label="label2")

marker_size = 36
def update_prop(handle, orig):
    handle.update_from(orig)
    handle.set_sizes([marker_size])

plt.legend(handler_map={type(sc): HandlerPathCollection(update_func=update_prop)})
plt.show()

enter image description here

关于python - 如何更改图例中散点标记的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47115869/

相关文章:

python - 如何在谷歌协作笔记本中显示 plotly 输出?

python - 多处理 : More processes than cpu. 计数

python - 无法标记多行 sns.catplot()

Matplotlib 图未显示在 Jupyter 笔记本第一个单元格的输出小部件中

python - 当图例只是数值时,如何使用 pyplot.scatter() 绘制图例?

matplotlib - dpi与图形尺寸的关系

python - 如何从python中的另一个数据框为新数据框赋值

python - doctest 中的链式异常

r - 如何在R中沿直线或曲线书写文本?

node.js - 根据位置和指定半径获取数据