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

如何在R中调整棒棒糖图间距并优化组合图表布局?

棒棒糖图布局优化与组合解决方案

问题概述

制作的棒棒糖图元素间距不均,生成对应a/b/c/d列的4张子图后用ggarrange组合过于拥挤,需要移除子图的"Gp A"/"Gp B"/"Gp C"/"Gp D"分组标签,并优化整体美观度。

优化代码方案

library(tidyverse)
library(ggpubr)
library(hrbrthemes) # 用于theme_ipsum

# 创建数据(设置随机种子保证结果可复现)
set.seed(123)
data <- data.frame(
    x=LETTERS[1:24],
    a=sample(1:30,24),
    b=sample(1:40,24),
    c=sample(1:50,24),
    d=sample(1:20,24,replace=T),
    gp=c("Gp A","Gp B","Gp C","Gp D")
)

# 宽数据转长格式,简化批量绘图流程
long_data <- data %>%
  pivot_longer(cols = c(a,b,c,d), names_to = "variable", values_to = "value") %>%
  arrange(value) %>%
  mutate(x = factor(x, levels = x)) # 按数值排序x轴元素

# 定义通用棒棒糖图绘制函数
plot_lollipop <- function(var_name) {
  long_data %>%
    filter(variable == var_name) %>%
    ggplot(aes(x = x, y = value)) +
    geom_segment(aes(x = x, xend = x, y = 0, yend = value), color = "grey50", linewidth = 0.8) +
    geom_point(aes(color = gp), size = 4) +
    geom_text(aes(label = value), color = "black", size = 2.8, vjust = -0.8) + # 调整文本位置避免遮挡
    coord_flip() +
    theme_ipsum(base_size = 9) + # 缩小基础字体缓解拥挤
    labs(title = str_to_title(var_name), y = "Number of articles", x = "") +
    theme(
      legend.position = "none", # 单个子图隐藏图例,后续统一添加
      panel.grid = element_blank(), # 移除网格线
      plot.margin = margin(5, 10, 5, 10, "pt"), # 调整子图边距
      strip.text.y = element_blank(), # 移除分组标签(coord_flip后facet位于y轴)
      axis.text.y = element_text(size = 7.5), # 缩小y轴文本
      axis.title.y = element_text(size = 8.5)
    ) +
    facet_grid(gp ~ ., scale = "free_y", space = "free_y") +
    scale_color_brewer(palette = "Set2") # 统一配色提升美观度
}

# 批量生成4张子图
fig_list <- map(c("a","b","c","d"), plot_lollipop)

# 组合图表并优化布局
combined_plot <- ggarrange(
  plotlist = fig_list,
  labels = c("A", "B", "C", "D"),
  ncol = 2, nrow = 2,
  common.legend = TRUE, # 共享图例节省空间
  legend = "bottom",
  align = "hv", # 水平垂直对齐子图
  widths = c(1,1), heights = c(1,1), # 统一子图尺寸
  hjust = -0.1, vjust = 1.2 # 调整标签位置避免遮挡
)

# 添加整体标题(可选)
annotate_figure(combined_plot, top = text_grob("Lollipop Plots Overview", face = "bold", size = 12))

关键优化点

  • 移除分组标签:通过theme(strip.text.y = element_blank())清除facet的分组文本(因coord_flip后facet行转为y轴方向)
  • 缓解拥挤问题:缩小基础字体、调整子图边距、共享图例避免重复占用空间,统一子图尺寸
  • 优化元素间距:调整geom_text的vjust参数避免文本遮挡数据点,使用统一配色提升视觉一致性
  • 简化代码:转长格式后用purrr::map批量生成子图,减少重复代码量

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 19:27:16