【发布时间】:2020-12-25 14:45:05
【问题描述】:
我有这个样本密度曲线数据(找到here):
library(tidyverse)
z <- rnorm(1000, mean = 0, sd = 1)
dens <- density(z)
data <- tibble(x = dens$x, y = dens$y) %>%
mutate(variable = case_when(
(x >= -2 & x <= 0) ~ "On",
(x >= 0.2 & x <= 1) ~ "Off",
TRUE ~ NA_character_))
我使用 ggplot2 绘制这条曲线,并使用 geom_area 绘制突出显示的区域,以及在绘图边界之外使用 geom_text 创建的一些文本,要求我关闭 coord_cartesian 中的剪辑:
ggplot(data, aes(x, y)) + geom_line() +
geom_area(data = filter(data, variable == 'On'), fill = 'grey') +
geom_area(data = filter(data, variable == 'Off'), fill = 'light blue') +
geom_text(aes(x = 7, y = 0.15, label = "test")) +
theme(plot.margin = unit(c(1,7,1,1), "lines")) +
coord_cartesian(xlim = c(-5, 5),
# ylim = c(0.1, 0.2),
clip = "off")
我现在想做的是放大 0.1 到 0.2 之间的 y 轴。我知道如果我在scale_y_continuous、then this can sometimes remove data which is constraining the view 中使用limits 参数,那么我在coord_cartesian 中使用ylim 参数设置为c(0.1, 0.2)。
但是,这会导致密度区域和曲线与绘图边界重叠(因为我已关闭剪裁)。
我现在可以做的是在coord_cartesian 中打开剪辑,但是现在这会删除我需要的绘图边界之外的 geom_text。有什么办法可以解决我的问题吗?
【问题讨论】: