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

如何将ggplot图例中颜色标识的周边区域改为图例背景色?

解决ggplot图例符号背景色问题

你要修改的是图例中每个颜色标识(符号)的背景区域,这个可以通过调整theme()里的legend.key参数实现,把它的填充色设为和图例背景一致的#FBF3E4即可。

修改后的完整代码如下:

movies <- read.csv(file.choose())

setwd("/Users/marimatiss/Desktop/R_course_Kirill/5. Advanced visualization")

colnames(movies) <- c("Film", "Genre", "CriticRating", 
     "AudienceRating", "BudgetMillions", "Year")

ggplot(movies) + 
  geom_point(mapping=aes(x=AudienceRating, y=CriticRating, 
  color=Year, fill=Year, size=BudgetMillions), alpha=0.6, shape=23) +
  scale_color_manual(values = c("#8A8635", "#AE431E", "#630000", 
     "#D8B6A4", "#105652")) +
  theme(panel.background = element_rect(fill="#FBF3E4"), 
        plot.background = element_rect(fill="#FBF3E4"), 
        legend.background = element_rect(fill="#FBF3E4"),
        # 设置图例符号的背景色,与图例背景统一
        legend.key = element_rect(fill="#FBF3E4"),
        panel.grid.major = element_blank(), 
        panel.grid.minor = element_blank()) +
  labs(title="Movie ratings", subtitle="by year")

补充说明

  • legend.key控制的是图例中每个符号所在的小方块背景色,默认是白色,改成和legend.background一致的颜色后,就能让符号周边区域和图例背景融为一体。
  • 如果想要进一步隐藏符号的边框,可以在legend.key里添加color = NA,比如legend.key = element_rect(fill="#FBF3E4", color=NA),这样符号的边框也会消失,视觉上更贴合背景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 13:30:54