Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restrict y-axis range on ggplot+geom_density

Tags:

r

ggplot2

I'm using geom_density to plot densities with very thin tails. I want to restrict the y-axis range (so the top of the distribution will be off screen and the tail is more clearly visible) but it's throwing away data that is off-screen when it calculate the density, rather than just not showing what is off screen.

E.g.

This plots the full distribution,

testData = data.frame(counts=c(rep(1,5), 1:10))
ggplot(testData, aes(x=testData$counts))+geom_density()

but when the y range is restricted, it looks as though the distribution has smaller support.

ggplot(testData, aes(x=testData$counts))+geom_density()+scale_y_continuous(limits=c(0,0.1))

How can I "zoom in" on the y axis without throwing away data?

like image 396
Pengin Avatar asked Oct 26 '10 18:10

Pengin


People also ask

How do I change y axis limits in R?

To change the axis scales on a plot in base R Language, we can use the xlim() and ylim() functions. The xlim() and ylim() functions are convenience functions that set the limit of the x-axis and y-axis respectively.

How do I change the y axis values in ggplot2?

Use scale_xx() functions It is also possible to use the functions scale_x_continuous() and scale_y_continuous() to change x and y axis limits, respectively.

What is the Y axis on a density plot?

The y-axis in a density plot is the probability density function for the kernel density estimation. However, we need to be careful to specify this is a probability density and not a probability. The difference is the probability density is the probability per unit on the x-axis.


1 Answers

I believe you're looking for coord_cartesian():

ggplot(testData, aes(x=testData$counts))+geom_density()+coord_cartesian(ylim=c(0, 0.1))
like image 56
danpelota Avatar answered Oct 07 '22 19:10

danpelota