You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Matplotlib绘图与图例中的标记尺寸保持一致?

解决Matplotlib图例标记与绘图标记尺寸不一致的问题

问题根源

ax.scatter()的s参数控制的是标记的面积(单位:平方点,1点=1/72英寸),而Line2D的markersize参数控制的是标记的线性尺寸(比如十字标记的长度,单位:点)。两者计算逻辑完全不同,直接将s的数值传给markersize,会导致图例标记尺寸明显偏大。

解决方案

将scatter使用的面积值转换为对应的线性尺寸,对面积取平方根即可(对于+这类线式标记,视觉匹配度最高)。

修改后的代码

import numpy as np
import numpy.random as rd
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D

rd.seed(12345)

fig,ax = plt.subplots()

# Number of time steps in each series
nb_steps = 5
t = np.linspace(1,nb_steps,nb_steps)

# Series 1
x1 = rd.random(nb_steps)
y1 = rd.random(nb_steps)

# Series 2
x2 = 1+2*rd.random(nb_steps)
y2 = 1+rd.random(nb_steps)

# Plotting with increasing marker size within series
marker_sizes = (t+3)**2
ax.scatter(x1,y1, marker = '+', s = marker_sizes)
ax.scatter(x2,y2, marker = '+', s = marker_sizes)

# Writing marker size legend
handles = []
# 将面积值转换为线性尺寸,取平方根匹配scatter的视觉效果
for size, step in zip(marker_sizes, t):
    handles.append(Line2D([0], [0], marker='+', lw=0, color='k', markersize=np.sqrt(size), label=step))

ax.legend(handles=handles, markerscale=1)
plt.show()

修改后,图例中的标记尺寸会和绘图中的标记完全一致,因为我们把scatter的面积参数转换成了Line2D对应的线性尺寸参数。

内容的提问来源于stack exchange,提问作者bercorvus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 04:12:47