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

如何在单图中按大洲和四分位数绘制双变量(柱状+散点)

单图展示各大洲四分位数的柱状图与次坐标轴散点解决方案

问题核心

移除facet_wrap(~continent)后,原代码的x轴仅映射为quartile,导致同一四分位数下不同大洲的柱状图重叠,散点也无法对应到各自大洲的柱子,因此需要调整x轴映射与元素对齐方式。

解决代码

library(ggplot2)
library(scales)

df <- read.table(header=TRUE, text="
continent quartile meantrans transcount
Africa 1 0.0241636 13
Africa 2 0.0324484 22
Africa 3 0.0761015 57
Africa 4 0.059952 50
Asia 1 0.0250368 17 
Asia 2 0.036566 23 
Asia 3 0.0465116 30
Asia 4 0.0521173 32
Europe 1 0 0 
Europe 2 0.0220884 11 
Europe 3 0.016632 8 
Europe 4 0.049676 23
North America 1 0 0 
North America 2 0 0 
North America 3 0 0 
North America 4 0.0285714 1 
Oceania 1 0 0 
Oceania 2 0.0235294 2 
Oceania 3 0 0 
Oceania 4 0 0 
South America 1 0.026738 10 
South America 2 0.0348525 13 
South America 3 0.0649038 27 
South America 4 0.058548 25 ")

ggplot(df, aes(x = factor(quartile), y = meantrans, fill = continent)) + 
  # 柱状图:设置position_dodge让同一四分位数下的大洲柱子并列
  geom_bar(stat = "identity", position = position_dodge(width = 0.8), width = 0.7) +
  # 散点图:使用相同的position_dodge保证与柱子对齐,映射transcount到次坐标轴
  geom_point(aes(y = transcount / 1000), shape = 21, size = 3, fill = "white", 
             position = position_dodge(width = 0.8)) +
  # x轴:设置为四分位数因子,显示1-4的标签
  scale_x_discrete(name = "Quartile", labels = c("1", "2", "3", "4")) +
  # 主y轴:百分比格式,对应meantrans
  scale_y_continuous(labels = percent, 
                     # 次y轴:还原缩放比例,对应transcount
                     sec.axis = sec_axis(~ . * 1000, name = "Transcount")) +
  labs(y = "Meantrans") +
  scale_fill_discrete(name = "Continent") +
  theme_bw() +
  theme(legend.position = "bottom")

关键调整说明

  • 将x = quartile改为x = factor(quartile),把四分位数转为分类变量,为同一分组下的大洲柱子并列提供基础。
  • 给geom_bar和geom_point都添加position = position_dodge(width = 0.8),确保散点与对应大洲的柱子严格对齐。
  • 调整柱子宽度width = 0.7,避免同一四分位数下的柱子过于拥挤。
  • 保持transcount / 1000的缩放比例,确保次坐标轴的数值与原始transcount匹配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 18:31:02