有条件的着色geom_smooth [英] Conditional colouring of a geom_smooth

查看:149
本文介绍了有条件的着色geom_smooth的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在分析一个围绕零变化的系列。要查看系列中哪些部分具有主要为正面或主要为负面的倾向,我正在绘制 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()

我考虑计算平滑值,将它们添加到df,然后使用 scale_color_gradient ,但我想知道是否存在直接在 ggplot 中实现这一点。

geom_smooth 中的 n 参数可以增加评估平滑点的点数,以便创建更多的y值接近于零。然后使用 ggplot_build ggplot 对象中获取平滑值。这些值用于 geom_line 中,该值添加在原始图的顶部。最后我们用 geom_hline 来计算y = 0的值。

 #具有大量平滑值的基本图
p < - ggplot(df,aes(x = x2,y = x1))+
geom_line()+
geom_smooth(linetype =blank ,n = 10000)

#抓取平滑值
df2 < - ggplot_build(p)[[1]] [[2]] [,c(x,y )]

#使用条件颜色添加平滑值
p +
geom_line(data = df2,aes(x = x,y = y,color = y> 0) )+
geom_hline(yintercept = 0)


I'm analyzing a series that varies around zero. And to see where there are parts of the series with a tendency to be mostly positive or mostly negative I'm plotting a geom_smooth. I was wondering if it is possible to have the color of the smooth line be dependent on whether or not it is above or below 0. Below is some code that produces a graph much like what I am trying to create.

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()

I considered calculating the smoothed values, adding them to the df and then using a scale_color_gradient, but I was wondering if there is a way to achieve this in ggplot directly.

解决方案

You may use the n argument in geom_smooth to increase "number of points to evaluate smoother at" in order to create some more y values close to zero. Then use ggplot_build to grab the smoothed values from the ggplot object. These values are used in a geom_line, which is added on top of the original plot. Last we overplot the y = 0 values with the 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)

这篇关于有条件的着色geom_smooth的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆