Pengin
Pengin

Reputation: 4772

Restrict y-axis range on ggplot+geom_density

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?

Upvotes: 12

Views: 15712

Answers (1)

danpelota
danpelota

Reputation: 2275

I believe you're looking for coord_cartesian():

ggplot(testData, aes(x=testData$counts))+geom_density()+coord_cartesian(ylim=c(0, 0.1))

Upvotes: 31

Related Questions