geom_smooth的条件着色

Mar*_*ing 10 r ggplot2

我正在分析一个在零附近变化的系列.并且看看该系列的哪些部分倾向于大多数是积极的或者大部分是负面的,我正在策划一个geom_smooth.我想知道是否有可能使平滑线的颜色取决于它是否高于或低于0.以下是一些产生图形的代码,就像我想要创建的一样.

set.seed(5)
r <- runif(22, max = 5, min = -5)
t <- rep(-5:5,2)
df <- data.frame(r+t,1:22)
colnames(df) <- c("x1","x2")
ggplot(df, aes(x = x2, y = x1)) + geom_hline() + geom_line() + geom_smooth()
Run Code Online (Sandbox Code Playgroud)

我考虑计算平滑值,将它们添加到df然后使用a scale_color_gradient,但我想知道是否有办法ggplot直接实现这一点.

Hen*_*rik 8

您可以使用n参数in geom_smooth来增加"要评估更平滑的点数",以便创建更接近零的y值.然后使用ggplot_buildggplot对象中获取平滑值.这些值用于a geom_line,它被添加到原始图的顶部.最后我们用y来超过y = 0的值geom_hline.

# basic plot with a larger number of smoothed values
p <- ggplot(df, aes(x = x2, y = x1)) +
  geom_line() +
  geom_smooth(linetype = "blank", n = 10000)

# grab smoothed values
df2 <- ggplot_build(p)[[1]][[2]][ , c("x", "y")]

# add smoothed values with conditional color
p +
  geom_line(data = df2, aes(x = x, y = y, color = y > 0)) +
  geom_hline(yintercept = 0)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


zx8*_*754 6

像这样的东西:

# loess data
res <- loess.smooth(df$x2, df$x1)
res <- data.frame(do.call(cbind, res))

res$posY <- ifelse(res$y >= 0, res$y, NA)
res$negY <- ifelse(res$y < 0, res$y, NA)

# plot
ggplot(df, aes(x = x2, y = x1)) + 
  geom_hline() + 
  geom_line() + 
  geom_line(data=res, aes(x = x, y = posY, col = "green")) +
  geom_line(data=res, aes(x = x, y = negY, col = "red")) +
  scale_color_identity()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • 我+ 1,因为这对于相当长而平滑的系列来说已经足够了(并且不会看到红绿色的间隙).我不知道如何解决这些问题:理想情况下,必须绘制另一条穿越y = 0的3点线,但这听起来太麻烦了.也许有另一种方法? (2认同)