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

移除ggplot组合图中geom_point图例的紫色背景

解决ggplot图例仅保留指定点标记的问题

你希望图例中仅显示「占年收入的比例」对应的黑色点标记,移除紫色背景的柱状图图例项,可通过以下修改实现:

核心改动思路

  • 将geom_col中设置边框颜色的color参数从aes()内移出(因为柱状图颜色是固定值,无需映射到图例)
  • 调整scale_color_manual,仅保留点标记对应的图例配置

修改后的完整代码

plotalimentacio_2021_decils <- ggplot(alimentacio_2021_decils) +
  # 把color参数移出aes,避免柱状图生成图例项
  geom_col(aes(fct_inorder(decils_renda), despesamonetaria), 
           fill="#9A6584", color="#9a6584", width=0.5, alpha=1) +                
  geom_point(aes(fct_inorder(decils_renda), proporcio_despesamonetaria_ingressos*100, 
                 color="Proporció sobre els ingressos anuals"), size=3) +
  # 仅保留点标记的图例配置
  scale_color_manual(name="", 
                     labels=c("占年收入的比例(右侧坐标轴)"), 
                     values=c("#000000")) +
  scale_y_continuous(labels=function(x) format(x, big.mark = ".", scientific = FALSE), 
                     breaks=seq(from=0, to=8000, by=1000),
                     expand = expansion(mult = c(0, .05)), 
                     sec.axis=sec_axis(~ ./100 ,  breaks = seq(0, 100, by = 10), 
                                       name = "% 占年收入总额")) +  
  geom_hline(yintercept=0, color="black")+
  labs(
    title="西班牙按收入十分位划分的食品支出(2021年)",
    subtitle="单位:欧元及占年收入的比例",
    x = "收入十分位", 
    y="",
    caption="来源:基于西班牙国家统计局(INE)2021年家庭预算调查(2016年基准)自制。") +
  theme(
    legend.position = "bottom",
    legend.justification = "left",
    legend.direction="horizontal",
    legend.margin=margin(t=-25),
    legend.text=element_text(size=12),
    legend.box.margin = margin(0,1,0.5,-1,"cm"))

改动说明

  1. geom_col调整:原本color="despesamonetaria"写在aes()内,会被ggplot识别为离散变量并生成图例项;移出后直接设置固定颜色,柱状图就不会出现在图例中。
  2. scale_color_manual调整:仅保留点标记对应的标签和黑色值,图例将只显示你需要的黑色点及对应说明。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 06:40:22