如何设置Matplotlib图例可变间距并让图例标记颜色匹配所用colormap
实现方案
- 匹配图例marker颜色与散点colormap
移除原代码中强制设置markerfacecolor为蓝色的逻辑,根据每个图例项对应的尺寸值,从散点对象的colormap中提取对应颜色即可。 - 设置递增的图例项间距
图例创建完成后,手动遍历调整每个图例文本和对应标记的垂直位置,实现间距递增效果。
完整修改后代码
import numpy as np import matplotlib.pyplot as plt N = 45 x, y = np.random.rand(2, N) s = np.random.randint(10, 1000, size=N) fig, ax = plt.subplots() scatter = ax.scatter(x, y, c=s, s=s) cbar = fig.colorbar(scatter, ax=ax, label='Size', fraction=0.1, pad=0.04) # 生成尺寸图例的handles和labels handles, labels = scatter.legend_elements(prop="sizes", alpha=0.6) # 只保留间隔采样的项 used_handles = handles[::2] used_labels = labels[::2] for hd, lab in zip(used_handles, used_labels): hd.set_markeredgewidth(2) hd.set_markeredgecolor("red") # 从标签提取尺寸数值,映射到colormap对应颜色 size_val = int(lab.split('$')[1]) normed_val = scatter.norm(size_val) hd.set_markerfacecolor(scatter.cmap(normed_val)) # 创建图例,labelspacing先设置为基础值 legend2 = ax.legend( used_handles, used_labels, loc="upper right", title="Sizes", labelspacing=1.2 ) # 调整图例项间距为递增 # 初始基准偏移 base_offset = 0 # 每次递增的间距增量,可根据需求调整 increment = 0.3 for i, text in enumerate(legend2.get_texts()): # 每一项在上一项基础上多增加increment的间距 base_offset += increment # 获取当前文本位置,调整y坐标 pos = text.get_position() text.set_position((pos[0], pos[1] - base_offset)) # 同步调整对应marker的位置 handle = legend2.get_lines()[i] handle_pos = handle.get_position() handle.set_position((handle_pos[0], handle_pos[1] - base_offset)) plt.show()
内容的提问来源于stack exchange,提问作者Khalil Al Hooti
相关产品推荐
相关产品推荐

