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

求助:图例与图表中的Marker样式不匹配问题

解决Seaborn折线图标记与图例样式不一致的问题

你设置的标记边框颜色、填充色、边框宽度等样式,只在图表的数据点上生效了,但图例里的标记没同步这些属性,所以出现样式不一致的情况。

下面是修复后的完整代码,核心是在绘制完图表后手动同步图例标记的样式:

import seaborn as sns
import matplotlib.pyplot as plt

sns.set_style(rc={'boxplot.flierprops.markeredgecolor':'black' ,'boxplot.flierprops.markeredgewidth':1.25,'boxplot.flierprops.markerfacecolor':'white'})
fig, ax = plt.subplots(figsize = (6,4), dpi = 100)
ax = sns.lineplot(data=df_whole, x='shortest_distance', y='similarity', 
                  style='Metric', hue='Metric', markers=True, lw=1,
                  markeredgewidth=1.25, markeredgecolor='black', 
                  markersize=7, dashes=False, errorbar=None, markerfacecolor='white')
ax.set(title='TF-IDF')
# 生成图例并获取图例对象
legend = ax.legend(title="Similarity Methods", prop={'size': 12})

# 遍历图例中的每个标记,同步样式
for handle in legend.legendHandles:
    handle.set_markeredgewidth(1.25)
    handle.set_markeredgecolor('black')
    handle.set_markerfacecolor('white')

plt.show()

重点说明

  • 把原代码里的scatter改成ax,更符合matplotlib的通用命名习惯
  • 通过legend.legendHandles获取图例里的所有标记元素,逐个设置和数据点一致的样式属性,就能让图例和图表标记样式统一了

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 16:51:37