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

Plotnine中如何移除geom_line()图例线条周围的伪框

解决plotnine图例线条周围伪框的方案

你看到的图例线条周围的伪框是plotnine默认图例键的边框样式,只需要在theme配置中新增legend_key参数即可移除。

修改方法

在你原有theme()的参数列表中新增一行配置即可:

legend_key = element_rect(fill='white', color=None)

如果你的画布背景不是白色,将fill参数值改为和画布背景一致的颜色即可,也可以设置为None使用透明背景。

修改后完整代码

import numpy as np
import pandas as pd
from plotnine import *


df = pd.DataFrame({
    'date':pd.date_range('1/1/2000', freq='A', periods=20),
    'a': np.random.uniform(0.01,0.03,20),
    'b': np.random.uniform(0.02,0.04,20),
})

df = pd.melt(df, id_vars=['date'])


p = (ggplot(df,aes(x='date',y='value',color='variable'))
  + theme_light()
  + geom_line(size=1.15)
  + labs(x=None, y=None)
  + scale_x_date(expand=(0,0), breaks=pd.date_range(start='2001-1-1', end='2019-1-1', periods=10), labels=lambda l: [v.strftime("%Y") for v in l])
  + scale_color_manual(('#50C878','#F75394'))
  + theme(
      legend_title=element_blank(),
      legend_direction='horizontal',
      legend_position='bottom',
      legend_box_spacing=0.25,
      legend_background=element_blank(),
      panel_grid_minor = element_blank(),
      panel_grid_major_x = element_blank(),
      panel_border = element_blank(),
      # 新增配置移除图例伪框
      legend_key = element_rect(fill='white', color=None)
  )
)
p

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 00:45:04