How to draw a clipped density plot in ggplot2 with

2019-08-02 07:17发布

问题:

I would like to use ggplot2 to draw a lattice plot of densities produced from different methods, in which the same yaxis scale is used throughout.

I would like to set the upper limit of the y axis to a value below the highest density value for any one method. However ggplot by default removes sections of the geom that are outside of the plotted region.

For example:

# Toy example of problem

xval <- rnorm(10000)

#Base1
plot(density(xval)) 
#Base2
plot(density(xval), ylim=c(0, 0.3)) # densities > 0.3 not removed from plot

xval <- as.data.frame(xval)

ggplot(xval, aes(x=xval)) + geom_density() #gg1 - looks like Base1
ggplot(xval, aex(x=xval)) + geom_density() + ylim(0, 0.3) 
#gg2: does not look like Base2 due to removal of density values > 0.3

These produce the images below:

How can I make the ggplot image not have the missing section?

回答1:

Using xlim() or ylim() directly will drop all data points that are not within the specified range. This yields the discontinuity of the density plot. Use coord_cartesian() to zoom in without losing the data points.

ggplot(xval, aes(x=xval)) + 
  geom_density() +  
  coord_cartesian(ylim = c(0, 0.3))


标签: r ggplot2