如何使用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_
相关产品推荐
相关产品推荐

