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

在R(ggplot2)中创建带自定义图例的气泡图问题求助

解决ggplot2气泡图的图例与气泡缩放问题

问题说明

用ggplot2绘制气泡图时遇到两个需求:

  • 图例位于右侧,每个研究的标记点显示病例数+对照数(而非研究编号),当前自定义图例标签未生效
  • 按比例放大气泡,减少图中空白区域

数据生成代码:

study_data <- data.frame(
  Year = c(2007, 2011, 2013, 2014, 2016, 2018, 2022),
  Positive_Associations = c(0, 2, 15, 17, 25, 40, 95),
  CaseSize = c(267, 5000, 12000, 15000, 19000, 26000, 37000),
  ControlSize = c(270, 8600, 21000, 50000, 95000, 403000, 1400000),
  Study = c(1, 2, 3, 4, 5, 6, 7)
)

修改后的完整代码

# 转换Study为因子,并创建自定义图例标签
study_data$Study <- as.factor(study_data$Study)
legend_labels <- paste("Cases:", study_data$CaseSize, ", Controls:", study_data$ControlSize)

# 绘制气泡图
p <- ggplot(study_data, aes(x = Year, y = Positive_Associations, size = Positive_Associations, color = Study)) +
  geom_point(alpha = 0.7) +
  geom_text(aes(label = Positive_Associations), color = "black", vjust = 0.5, size = 3) +
  # 调整气泡大小范围,按比例放大;同时隐藏大小图例
  scale_size_continuous(range = c(5, 18), guide = "none") +
  # 设置颜色调色板,并直接指定图例标签
  scale_color_brewer(palette = "Dark2", labels = legend_labels) +
  labs(title = "Evolution of studies",
       x = "Year",
       y = "Number of Positive Associations") +
  theme_minimal() +
  # 设置图例位置在右侧,移除图例标题
  theme(legend.position = "right", legend.title = element_blank()) +
  # 调整坐标轴范围,减少空白区域
  coord_cartesian(xlim = c(2006, 2023), ylim = c(-5, 100), expand = FALSE)

print(p)

关键修改说明

  1. 图例标签生效:

    • 将自定义标签直接传入scale_color_brewer的labels参数,替代原代码中在guides内设置的方式,确保标签正确映射到每个研究
    • 通过theme(legend.title = element_blank())移除图例标题,让布局更简洁
  2. 气泡缩放与减少空白:

    • 增大scale_size_continuous的range参数(如从c(3,12)改为c(5,18)),按比例放大气泡
    • 使用coord_cartesian设置坐标轴范围并关闭expand,减少图表四周的空白区域,让气泡布局更紧凑
    • 在scale_size_continuous中设置guide = "none",直接隐藏大小图例,无需额外guides配置

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 20:12:34