我的数据如下。两栏,序列号(SL)和表达值(log)
> df
SL log
1 1.5
2 -2.5
3 1.0
4 2.5
5 -1.
> ggplot(df, aes(x = SL, y = log)) +
geom_point(size = 0.5, alpha = 0.6, shape = 19, color = "gray") +
geom_smooth(method = "loess", se = FALSE, linewidth = 0.5, span = 0.09) +
geom_hline(yintercept = 0, color = "black", lwd = 0.5)
但是,我想填充 geome_smooth 黄土线,如果它位于 Y=0 截距线上方,则填充红色,如果低于 Y=0 截距线,则填充绿色。示例如下图。
我该怎么做
给出一些虚假数据:
df <- data.frame(x = 1:100,
y = sin(seq(0,8, length.out = 100)) + sin(1:100))
我们可以使用here的方法绘制并提取黄土曲线:
p <- ggplot(df, aes(x, y)) +
geom_point() +
geom_smooth()
df2 <- ggplot_build(p)[[1]][[2]][,c("x","y")]
然后我们遇到了一个涉及插值的稍微棘手的问题,详见here和here。我认为最简单的解决方案可能是依赖
ggh4x
或 ggbraid
包中预先存在的解决方案。我从 ggbraid
解决方案中获得了更清晰的结果,该解决方案可识别精确的交叉点并干净地分隔填充区域。
ggplot(df, aes(x, y)) +
geom_point() +
ggh4x::stat_difference(aes(ymin = 0, ymax = y, fill = y < 0),
data = df2)
# remotes::install_github("nsgrantham/ggbraid")
ggplot(df, aes(x, y)) +
geom_point() +
ggbraid::stat_braid(aes(x, ymin = 0, ymax = y, fill = y < 0),
data = df2)