如何限制ggplot2中图层的显示 [英] How to limit the display of a layer in ggplot2

查看:120
本文介绍了如何限制ggplot2中图层的显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个包含两个图层,一个geom_point和一个stat_smooth的图,我怎么能限制stat_smooth图层只显示一个特定的x轴坐标?



这是一个简单的工作示例:
http:// www.r-fiddle.org/#/fiddle?id=qfnAsk3H&version=4

  library(ggplot2 )
p <-ggplot()+ geom_point(data = mtcars,aes(x = wt,y = mpg))
p + stat_smooth(data = mtcars,aes(x = wt,y = mpg) )

假设我只希望stat_smooth从x = 3到图的最后显示。 p>

可以这样做吗?



如果我创建一个限制为x> = 3的mtcars副本并将其用作stat_smooth的数据,它会改变我不能拥有的趋势线(最后变胖)。我只是想掩盖它,或者只显示部分x> = 3。

解决方案

您可以从原始使用 ggplot_build 进行绘图。这将为您提供可用于根据需要重新生成 stat_smooth 的数据点。我在这里使用了 geom_line 一个 geom_ribbon ,也许还有其他方法可以做到这一点。

  library(ggplot2)
mtcars_plus_three< - mtcars [mtcars $ wt> 3,]
p < - ggplot()+ geom_point(data = mtcars,aes(x = wt,y = mpg))
p_full < - p + stat_smooth(data = mtcars,aes(x = wt,y = mpg))

data_full_range < - ggplot_build(p_full)$ data [[2]]
data_full_range < - data_full_range [data_full_range $ x> 3,]
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)


Given a plot with two layers, a geom_point and a stat_smooth, how can I limit the stat_smooth layer to only display for a particular span of the x-axis?

Here's a simple working example: http://www.r-fiddle.org/#/fiddle?id=qfnAsk3H&version=4

library(ggplot2)
p <- ggplot() + geom_point(data=mtcars, aes(x=wt, y=mpg))    
p + stat_smooth(data=mtcars, aes(x=wt, y=mpg)) 

Say I only want stat_smooth to show from x=3 to the end of the graph.

Can this be done?

If I create a copy of mtcars limited to x>=3 and use that as the data for stat_smooth, it will change the trendline (it gets fat at the end) which I can't have. I just want to mask it, or only display the portion x>=3.

解决方案

You can obtain the data from the original plot using ggplot_build. This will provide you with the datapoints that can be used to rebuild the stat_smooth on the interval you want. I have use geom_line an geom_ribbon here, perhaps there are other ways to do it too.

library(ggplot2)
mtcars_plus_three <- mtcars[mtcars$wt > 3, ]
p <- ggplot() + geom_point(data=mtcars, aes(x=wt, y=mpg))
p_full <- p + stat_smooth(data=mtcars, aes(x=wt, y=mpg)) 

data_full_range <- ggplot_build(p_full)$data[[2]]
data_full_range <- data_full_range[data_full_range$x > 3, ]
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)

这篇关于如何限制ggplot2中图层的显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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