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

如何修改legend(图例)的文本颜色,使图例文字与对应线条颜色一致?

图例文字颜色与对应图形元素同色的实现方法

Python Matplotlib 场景

折线/线条类图形

  • 先正常绘制图形,获取生成的图例对象
  • 遍历图例的线条样本和对应文本,同步颜色设置
    示例代码:
import matplotlib.pyplot as plt

# 基础绘图逻辑
fig, ax = plt.subplots()
line1, = ax.plot([1,2,3], [4,5,1], color='#e63946', label='曲线A')
line2, = ax.plot([1,2,3], [2,3,4], color='#1d3557', label='曲线B')
line3, = ax.plot([1,2,3], [3,1,2], color='#457b9d', label='曲线C')

# 获取图例对象
leg = ax.legend()

# 同步文字与线条颜色
for line, text in zip(leg.get_lines(), leg.get_texts()):
    text.set_color(line.get_color())

plt.show()

柱状/填充类图形

填充类图形的图例样本存储在get_patches()方法返回的列表中,替换对应方法即可:

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(3)
y1 = [2,5,3]
y2 = [3,4,2]

fig, ax = plt.subplots()
ax.bar(x, y1, color='#fca311', label='柱组A')
ax.bar(x, y2, bottom=y1, color='#14213d', label='柱组B')

leg = ax.legend()
for patch, text in zip(leg.get_patches(), leg.get_texts()):
    text.set_color(patch.get_facecolor())

plt.show()

Python Seaborn 场景

Seaborn基于Matplotlib封装,逻辑完全通用,只需拿到绘图返回的坐标轴对象的legend_属性即可:

import seaborn as sns
import matplotlib.pyplot as plt

# 内置示例数据集
tips = sns.load_dataset("tips")
ax = sns.lineplot(data=tips, x="day", y="total_bill", hue="sex")

# 同步颜色
leg = ax.legend_
for line, text in zip(leg.get_lines(), leg.get_texts()):
    text.set_color(line.get_color())

plt.show()

R ggplot2 场景

借助ggtext包的富文本渲染能力即可实现,示例代码:

library(ggplot2)
library(ggtext)
library(glue)

ggplot(mpg, aes(displ, hwy, color = class)) +
  geom_point() +
  scale_color_discrete(
    labels = ~ glue("<span style='color:{.color}'>{.x}</span>")
  ) +
  theme(
    legend.text = element_markdown(),
    legend.key = element_rect(fill = NA)
  )

内容的提问来源于stack exchange,提问作者Friedrich -- Слава Україні

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 08:36:04