如何使用ggplot2将geom置于绘图边距以高亮x值区间?
问题
我希望在x轴下方绘制一个geom(一组条形图),用于高亮显示感兴趣的x值区间。目前我通过完全关闭坐标轴并在绘图区域内绘制geom实现了需求,但需要手动逐个添加坐标轴元素(线条、刻度、标签)。是否可以直接使用ggplot2将这些条形图绘制在绘图边距中?
现有实现代码:
library("tidyverse") data <- tribble( ~x_start, ~x_end, ~y, ~label, 1, 5, 9, "A", 3, 6, 8, "B", 8, 11, 5, "C", 9, 12, 6, "D" ) data %>% ggplot() + # Add fake x-axis. geom_hline( yintercept = 0 ) + # Add segments "inside the plotting area". geom_segment( aes( x = x_start, y = y, xend = x_end, yend = y, color = label ), size = 2 ) + # Add tiles "inside the margins". geom_rect( aes( xmin = x_start, ymin = 0, xmax = x_end, ymax = -1, fill = label ), alpha = 0.5 ) + theme_minimal() + theme( axis.title = element_blank(), axis.text.x = element_blank(), axis.ticks = element_blank(), panel.grid = element_blank(), legend.position = "none" )
解决方案
可以借助patchwork包将主绘图与下方的高亮条形图拼接,既能保留原生坐标轴的所有元素,又能把高亮区域放在x轴下方的边距位置,无需手动绘制坐标轴。具体实现代码如下:
library("tidyverse") library("patchwork") data <- tribble( ~x_start, ~x_end, ~y, ~label, 1, 5, 9, "A", 3, 6, 8, "B", 8, 11, 5, "C", 9, 12, 6, "D" ) # 绘制主图 main_plot <- data %>% ggplot() + geom_segment( aes(x = x_start, y = y, xend = x_end, yend = y, color = label), size = 2 ) + theme_minimal() + theme( panel.grid = element_blank(), legend.position = "none", axis.title.x = element_blank(), plot.margin = margin(10, 10, 0, 10) # 调整底部边距,避免与下方图重叠 ) # 绘制下方的高亮条形图 margin_plot <- data %>% ggplot() + geom_rect( aes(xmin = x_start, xmax = x_end, ymin = 0, ymax = 1, fill = label), alpha = 0.5 ) + scale_y_continuous(limits = c(0, 1), expand = c(0, 0)) + theme_minimal() + theme( axis.text = element_blank(), axis.title = element_blank(), axis.ticks = element_blank(), panel.grid = element_blank(), legend.position = "none", plot.margin = margin(0, 10, 10, 10) # 调整顶部边距,避免与上方图重叠 ) # 拼接两个图,设置高度比例 main_plot / margin_plot + plot_layout(heights = c(4, 1))
说明
- 主图保留原生x轴的刻度、标签和线条,无需手动添加
- 高亮条形图作为独立子图,隐藏所有无关元素,仅保留高亮矩形
- 通过
plot_layout设置主图与高亮图的高度比例,确保视觉协调 - 调整两个图的
plot.margin参数,避免拼接后出现间距过大或重叠的问题
内容的提问来源于stack exchange,提问作者dipetkov
相关产品推荐
相关产品推荐

