4
votes

I am creating a plot in ggplot2 with filled densities, a few of which I would like to truncate. I apologize for lack of images--apparently I'm not allowed to post them yet. A simple example of beginning code:

dd = with(density(rnorm(100,0,1)),data.frame(x,y))

ylimit = .3

ggplot(data = dd, mapping = aes(x = x, y = y), geom="line") +
 layer(data = dd, mapping = aes(x = x, y = y), geom = "area", 
       geom_params=list(fill="red",alpha=.3)) +
         scale_x_continuous(limits = c(-3,3)) +
         scale_y_continuous(limits = c(0,ylimit)) 

This, however, results in an empty area in the middle of the filled density where dd$y > ylimit.

If I compensate for this with

dd$y = pmin(dd$y, ylimit)

The area is shaded but the plot displays an area slightly higher than ylimit, so the fill does not extend to the top of the graph.

Ideally I would like to know how to get ggplot display a plot exactly up to ylimit, but any other solutions for having the fill extend to the top of the plot would be welcome.

Edit:fixed the code.

1
This code does not work for me. Could you check it and edit?John Colby
This link might also be useful to demonstrate the difference between "coord" and "scale" in ggplot2. had.co.nz/ggplot2/coord_cartesian.htmlJohn Colby

1 Answers

4
votes

I think this is what you meant. Note the use of ifelse to get the truncating behavior.

dd = with(density(rnorm(100,0,1)), data.frame(x, y))

ylimit = .3

dev.new(width=4, height=4)
ggplot(data = dd, mapping = aes(x = x, y = y), geom="line") +
 layer(data = dd, mapping = aes(x = x, y = ifelse(y>ylimit, ylimit, y)), geom = "area", 
       geom_params=list(fill="red",alpha=.3)) +
         scale_x_continuous(limits = c(-3,3)) +
         coord_cartesian(ylim=c(0, ylimit))

enter image description here