如何在ggplot中缩小矩形尺寸且维持布局规整?
解决ggplot矩形过大且调整偏移量导致布局错乱的问题
问题分析
原代码里用x - 0.5和x + 0.5定义矩形边界时,矩形刚好彼此衔接(因为x轴坐标间隔为1)。直接把偏移量改成更小的值(比如0.2)后,矩形宽度缩小,但x轴坐标间隔仍为1,相邻矩形之间会出现明显空隙,看起来“分离错乱”。
解决方案
要缩小矩形同时保持布局整齐,只需用统一的较小偏移量调整矩形边界,让每个矩形围绕原坐标中心等比例缩小即可。这种方式下,矩形间虽会出现间隙,但整体排列依然规整,不会出现错乱。
如果希望矩形保持紧凑衔接,可以调整x/y坐标的间隔,使其等于偏移量的2倍(比如偏移量用0.3,坐标间隔就设为0.6),但这种方法需要修改原数据的坐标值,适合对坐标数值无特定要求的场景。
修改后的代码
library(tidyverse) df <- bind_rows( expand_grid(x = 1:5, y = c(1, 2.2)), expand_grid(x = 8:12, y = c(1, 2.2)) ) %>% arrange(y, x) %>% mutate( num = c(c(1, 0, 1, 1, 0), c(1, 0, 0, 1, 0), c(0, 1, 0, 1, 0), c(0, 1, 1, 1, 0)), fill_color = ifelse(row_number() %in% c(c(11,12,13,14,15), c(16,17), c(8,9,10)), "skyblue", "white") ) # 使用0.3作为偏移量,缩小矩形尺寸且保持布局整齐 ggplot(df) + geom_rect(aes(xmin = x - 0.3, xmax = x + 0.3, ymin = y - 0.3, ymax = y + 0.3, fill = fill_color), color = "black") + geom_text(aes(x = x, y = y, label = num)) + geom_segment(aes(x = 2.5, xend = 2.5, y = .4, yend = 2.8), arrow = arrow(length = unit(5, "pt"))) + geom_segment( aes(x = 5.7, xend = 7.3, y = 1.6, yend = 1.6), linewidth = 3, lineend = "round", linejoin = 'round', color = "black", arrow = arrow(length = unit(9, "pt"), type = "open") ) + scale_fill_manual(values = c("skyblue", "white")) + ylim(0, 4) + xlim(0, 13) + theme_void() + theme( panel.background = element_rect(fill = 'white'), plot.margin = unit(c(0, 0, 0, 0), "pt"), legend.position = "none" )
说明
- 这里把偏移量从0.5改为0.3,矩形宽高从1缩小到0.6,每个矩形都围绕原x/y中心缩放,文字与矩形的对齐关系完全保留。
- 你可以根据需求灵活调整偏移量大小(比如0.2、0.35等),找到最适配的矩形尺寸。
内容的提问来源于stack exchange,提问作者Carlo Soares
相关产品推荐
相关产品推荐

