使用annotate()绘制的阴影区域无法覆盖绘图完整高度的解决方法
问题描述
我用ggplot2绘制了带阴影区域的图形,代码如下:
library(ggplot2) xmin <- 6 xmax <- 7 ymin <- min(iris$Sepal.Width) ymax <- max(iris$Sepal.Width) p <- iris |> ggplot(aes(Sepal.Length, Sepal.Width)) + annotate( "rect", xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax, fill='pink', alpha=0.5 ) + geom_point() p
即便取了iris数据集Sepal.Width的最大最小值作为y轴范围,阴影区域还是没法覆盖绘图的完整高度,但geom_vline()却能做到全屏延伸,示例代码:
p + geom_vline(xintercept = 5)
想知道有没有简便方法让阴影区域覆盖绘图的整个高度?
解决方案
方法1:用Inf和-Inf代替具体数值
直接把ymin设为-Inf,ymax设为Inf,矩形会自动延伸到绘图区域的上下边界,无需手动计算数据极值:
library(ggplot2) xmin <- 6 xmax <- 7 p <- iris |> ggplot(aes(Sepal.Length, Sepal.Width)) + annotate( "rect", xmin = xmin, xmax = xmax, ymin = -Inf, ymax = Inf, fill='pink', alpha=0.5 ) + geom_point() p
方法2:使用geom_rect配合全局数据框
如果需要更灵活的控制,也可以用geom_rect,指定包含范围的全局数据框,同样用Inf覆盖y轴范围:
library(ggplot2) p <- iris |> ggplot(aes(Sepal.Length, Sepal.Width)) + geom_rect( data = data.frame(xmin=6, xmax=7), aes(xmin=xmin, xmax=xmax, ymin=-Inf, ymax=Inf), fill='pink', alpha=0.5, inherit.aes = FALSE ) + geom_point() p
内容的提问来源于stack exchange,提问作者bretauv
相关产品推荐
相关产品推荐

