从ggplot_build数据重新创建ggplot图层,其中color = some_discrete_value

时间:2015-08-28 18:23:16

标签: r ggplot2

我有一个情节,其中趋势线已被掩盖&#34;到一个特定的域,在这个例子中x <1.5,通过创建stat_smooth图层,将其转换为数据,并在x <1.5时切断数据(感谢this answer

library(ggplot2)
mysample <- diamonds[sample(1:nrow(diamonds), 500,   replace=FALSE),] 

p <- ggplot() + geom_point(data=mysample, aes(x=carat, y=price))
p_full <- p + stat_smooth(data=mysample, aes(x=carat, y=price)) 

data_full_range <- ggplot_build(p_full)$data[[2]]
data_full_range <- data_full_range[data_full_range$x < 1.5, ]
p + geom_line(data = data_full_range, aes(x = x, y = y), col = 'blue') +
geom_ribbon(data = data_full_range, aes(x=x, ymin=ymin, ymax = ymax), alpha = .5)

我需要做同样的事情,但是用一些参数分隔趋势。例如,通过清晰度:

library(ggplot2)
#just to limit data making it easier to see what's going on
mysample <- diamonds[sample(1:nrow(diamonds), 1000,   replace=FALSE),] 

p <- ggplot() + geom_point(data=mysample, aes(x=carat, y=price, color=clarity))
p + stat_smooth(data=mysample, aes(x=carat, y=price, color=clarity)) 

我如何做与第一个脚本相同的操作;屏蔽x <1.5处的趋势,但是数据是否像第二个脚本一样分开?

1 个答案:

答案 0 :(得分:1)

添加清晰度作为分组变量,然后在重新创建图形时使用group = group。

p <- ggplot() + geom_point(data=mysample, aes(x=carat, y=price))
p_full <- p + stat_smooth(data=mysample, aes(x=carat, y=price,group=clarity)) 

data_full_range <- ggplot_build(p_full)$data[[2]]
data_full_range <- data_full_range[data_full_range$x < 1.5, ]
p + geom_line(data = data_full_range, aes(x = x, y = y, group=group), col = 'blue') +
    geom_ribbon(data = data_full_range, aes(x=x, ymin=ymin, 
    ymax = ymax, group = group), alpha = .5)

可以使用p_full来测试趋势是否符合原始模式。

p_full + geom_line(data = data_full_range, aes(x = x, y = y, group=group), col = 'blue') +
geom_ribbon(data = data_full_range, aes(x=x, ymin=ymin, ymax = ymax,
            group = group), alpha = .5)