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

R语言中水平匹配两个ggplot并实现排序与布局优化

解决gglikert图与条形图的排序、对齐及图例统一问题

1. 按smoke+vaping合计占比降序排列g1的国家(合计高的在最下方)

先计算各国家两类行为的合计占比,再重新设定country的因子水平(升序排列合计值,让高占比国家落在y轴底部):

# 假设原始数据框为df,包含country、smoke、vaping列
library(dplyr)

# 计算合计并排序得到国家顺序
sorted_countries <- df %>%
  group_by(country) %>%
  summarise(total = sum(smoke, vaping, na.rm = TRUE)) %>%
  arrange(total) %>%  # 升序排列,对应y轴从低到高(高合计在底部)
  pull(country)

# 更新数据的因子水平,重绘g1
df$country <- factor(df$country, levels = sorted_countries)
g1 <- gglikert(df, ...)  # 替换为你原有的gglikert绘图代码

2. 统一两图国家顺序,实现垂直高度一一对应

把g2数据的country因子水平设置为和g1完全一致,确保y轴国家位置匹配:

# 假设g2的数据源为g2_data
g2_data$country <- factor(g2_data$country, levels = sorted_countries)

# 重绘g2(注意y轴绑定country,和g1保持一致)
g2 <- ggplot(g2_data, aes(x = your_value, y = country)) +
  geom_bar(stat = "identity") +
  ...  # 你的其他条形图配置

3. 以g1为基准匹配两图高度

使用ggarrange的align = "v"参数实现垂直对齐,若g1有特殊高度需求,可通过heights参数指定比例:

library(ggpubr)

# 先隐藏两图各自的图例,后续统一添加
aligned_plots <- ggarrange(
  g1 + theme(legend.position = "none"),
  g2 + theme(legend.position = "none"),
  align = "v",  # 强制垂直对齐
  ncol = 2,
  heights = c(1, 1)  # 以g1为基准,保持两图高度一致,可按需调整比例
)

4. 统一图例放置在底部

两种实现方式,按需选择:

方式1:直接用ggarrange的通用图例参数

如果两图图例内容一致,可直接指定:

final_plot <- ggarrange(
  g1,
  g2,
  align = "v",
  ncol = 2,
  common.legend = TRUE,
  legend = "bottom"
)

方式2:手动提取图例后添加

如果两图图例内容不同,先提取g1的图例再组合:

# 提取g1的图例
g1_legend <- get_legend(g1)

# 将图例添加到对齐后的图底部
final_plot <- annotate_figure(
  aligned_plots,
  bottom = g1_legend
)

内容的提问来源于stack exchange,提问作者Homer Jay Simpson

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 09:24:57