r语言 - 从ggplot_build数据重新创建一个ggplot层,其中color = some_discrete_valu



我有一个图,其中趋势线被"屏蔽"到一个特定的域,在这个例子中是x<1.5,通过创建stat_smooth层,将其转换为数据,并在x<1.5处切断数据(感谢这个答案)

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的趋势,但像第二个脚本那样将数据分开?

添加clarity作为分组变量,然后在重新创建图形时使用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)

最新更新