Truncate density curve in ggplot

198 views
Skip to first unread message

Jens Stevens

unread,
Oct 2, 2015, 6:52:51 PM10/2/15
to Davis R Users' Group
Consider the following example:
ggplot(mtcars)+
  geom_point(aes(y=mpg, x=wt,col=factor(cyl)))+
  geom_density(aes(x=wt,y=..scaled..*30,col=factor(cyl)))

Is there a way to truncate a density curve in ggplot so that it does not extend past the limits of the data? This is most relevant when multiple density curves are present, and refer to different subsets of the data. For instance, eliminate the right tail of the red curve in the example above, and instead immediately drop the density to zero. In the case that I am applying this example to, the data is for an entire population rather than a sample, so having a non-zero density estimate beyond the limits of the data is unrealistic.

Cheers
Jens

Noam Ross

unread,
Oct 2, 2015, 8:35:31 PM10/2/15
to Davis R Users' Group

Yes, the argument trim=TRUE does exactly this:

ggplot(mtcars)+
  geom_point(aes(y=mpg, x=wt,col=factor(cyl)))+
  geom_density(aes(x=wt,y=..scaled..*30,col=factor(cyl)), trim=TRUE)

This is documented in ?stat_density.


--
Check out our R resources at http://www.noamross.net/davis-r-users-group.html
---
You received this message because you are subscribed to the Google Groups "Davis R Users' Group" group.
To unsubscribe from this group and stop receiving emails from it, send an email to davis-rug+...@googlegroups.com.
Visit this group at http://groups.google.com/group/davis-rug.
For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages