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

ggplot2双Y轴图图例自定义:移除条形图图例点标记

双Y轴图图例精准控制方案

需求说明

需要对ggplot2绘制的双Y轴图做图例精细化控制:

  • 上方对应**堆叠条形图(总资金占比)**的图例:仅显示类别颜色块,不显示点标记
  • 下方对应**折线图(项目数量)**的图例:显示线条+带填充色的形状

修改后的实现代码

library(tidyverse)
library(openxlsx)
library(ggplot2)
library(cowplot)

# 加载数据
new_data = read.xlsx("processed_2008-2020.xlsx")

max_projects <- max(new_data$number_of_projects, na.rm = TRUE)

# 创建主图
main_plot <- new_data %>%
  ggplot(aes(x = year)) +
  geom_bar(
    aes(y = pct_total_funding * 100, fill = category),
    stat = "identity",
    position = "stack",
    alpha = 0.6
  ) +
  geom_line(
    aes(y = number_of_projects * (100 / max_projects), group = category),
    color = "black",
    linewidth = 0.7,
    alpha = 0.7
  ) +
  geom_point(
    aes(y = number_of_projects * (100 / max_projects), shape = category, fill = category),
    color = "black",  # 形状描边设为黑色
    size = 3,
    stroke = 0.5,
    alpha = 0.7
  ) +
  scale_shape_manual(values = c(21, 22, 23, 24)) +
  scale_fill_brewer(palette = "Dark2") +
  scale_x_continuous(
    name = "Funding Year",
    breaks = unique(new_data$year),
    labels = function(x) str_glue("{x}")
  ) +
  scale_y_continuous(
    name = "Percentage of Total Funding",
    breaks = seq(0, 100, by = 20),
    minor_breaks = seq(0, 100, by = 10),
    labels = percent_format(scale = 1),
    sec.axis = sec_axis(~ . * (max_projects / 100),
                        name = "Number of Projects",
                        labels = scales::comma_format()),
    limits = c(0, NA),
    expand = expansion(mult = c(0, 0.05))
  ) +
  labs(
    title = "US Autism Research Funding by Category",
    subtitle = "Federal and Private",
    fill = "Percentage of Total Funding",
    shape = "Number of Projects"
  ) +
  theme_light() +
  theme(
    plot.title = element_text(hjust = 0.5),
    plot.subtitle = element_text(hjust = 0.5),
    legend.position = "bottom",
    legend.box = "vertical",  # 图例上下堆叠排列
    legend.title = element_text(size = 12),
    legend.text = element_text(size = 11),
    axis.text.x = element_text(angle = 45, hjust = 1),
    panel.grid.major.x = element_blank(),
    panel.grid.minor.x = element_blank(),
    panel.border = element_blank(),
    axis.ticks.y = element_blank()
  )

# 精准控制图例显示样式
main_plot <- main_plot + 
  guides(
    # 条形图图例:隐藏点标记,仅保留颜色块
    fill = guide_legend(
      title = "Percentage of Total Funding",
      override.aes = list(shape = NA)
    ),
    # 折线图图例:显示线条+带填充色的形状,匹配图表样式
    shape = guide_legend(
      title = "Number of Projects",
      override.aes = list(
        color = "black",  # 线条颜色与geom_line保持一致
        fill = scale_fill_brewer(palette = "Dark2")$values  # 填充色与条形图类别对应
      )
    )
  )

# 输出最终图表
print(main_plot)

核心修改说明

  • 针对fill图例,通过override.aes = list(shape = NA)直接隐藏点标记,只保留类别颜色块
  • 针对shape图例,用override.aes指定线条颜色为黑色,并复用条形图的填充色,保证形状与对应类别的颜色统一
  • 保留原有主题配置,维持图例上下堆叠的布局结构

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 08:51:02