You need to enable JavaScript to run this app. 如何使用grid.arrange实现零间距拼接镜像ggplot柱状图
优惠活动
大模型
产品
解决方案
定价
更多

如何使用grid.arrange实现零间距拼接镜像ggplot柱状图

镜像ggplot柱状图无缝拼接解决方案

你可以通过调整图表边距+使用patchwork拼接包的方式实现需求,最终支持PlotLR <- PL + PR的调用形式,完整可运行代码如下:

# 加载必要包
library(ggplot2)
library(patchwork)

# 原始数据
DWP1 <- data.frame("City" = c("Berlin", "Paris", "London"),
                   "People" = c(3.3, 2.1, 9))
DWP2 <- data.frame("City" = c("New York", "Washington", "Miami"),
                  "People" = c(8.4, 0.7, 0.4))
# 定义字体变量(匹配原代码引用的Schriftart,可替换为你实际使用的字体)
Schriftart <- "sans"

# 右侧图PR
PR <- ggplot(DWP1, aes(x = reorder(City, People), y = People))+
  geom_col(aes(fill = City), width = 0.1, position =  position_dodge(-0.9), linetype="dotted")+
  coord_flip()+
  scale_y_continuous(expand = expansion(mult = c(0, .1)), limits = c(0, 10)) + # 固定y轴范围保证对齐
  theme(
    axis.line = element_line(),
    panel.background = element_rect(fill = "transparent", color = NA),
    plot.background = element_rect(fill= "transparent", color = NA),
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(),
    panel.border = element_blank(),
    legend.position = "none",
    axis.title = element_blank(),
    axis.text = element_blank(),
    axis.ticks = element_blank(),
    axis.line.x = element_blank(),
    # 核心修改:左侧边距设为0,消除和左图的空隙
    plot.margin = unit(c(0,5,0,0), "pt")
  )

# 左侧图PL
PL <- ggplot(DWP2, aes(x = reorder(City, People), y = People))+
  geom_col(aes(fill = City), width = 0.1)+
  coord_flip()+
  # 合并scale_y配置,避免重复定义冲突,同时固定y轴范围
  scale_y_reverse(expand = expansion(mult = c(0, .1)), limits = c(10, 0)) +
  theme(
    axis.line = element_line(),
    panel.background = element_rect(fill = "transparent", color = NA),
    plot.background = element_rect(fill= "transparent", color = NA),
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(),
    panel.border = element_blank(),
    legend.position = "none",
    axis.title = element_blank(),
    axis.text = element_blank(),
    axis.ticks = element_blank(),
    axis.line.x = element_blank(),
    axis.line.y = element_blank(),
    # 核心修改:右侧边距设为0,消除和右图的空隙
    plot.margin = unit(c(0,0,0,5), "pt")
  )

# 直接用加号拼接,生成最终对象PlotLR
PlotLR <- PL + PR + plot_layout(nrow = 1)

关键修改说明

  • 消除了原代码中scale_y_continuous和scale_y_reverse重复定义的冲突,将expand参数统一写入scale_y_reverse
  • 新增plot.margin配置,将左图右侧、右图左侧的边距设为0,彻底消除两张图拼接处的空隙
  • 固定两张图的y轴范围,保证拼接后柱体高度对齐
  • 使用patchwork包实现你需要的PL + PR语法拼接,plot_layout默认无额外间距,符合无缝拼接需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 19:33:00