Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot add ticks to each plot in a facet_wrap

I'd like to display x-axis ticks on plots in the upper rows in facet_wraps. For example:

library(ggplot2)
ggplot(diamonds, aes(carat)) +  facet_wrap(~ cut, scales = "fixed") +  geom_density()

generates this plot:

Actual Plot

I'd like to have ticks as I've drawn in on this plot: Desired Plot

Is there a simple way to achieve this result?

like image 952
conor Avatar asked Jan 23 '17 02:01

conor


1 Answers

Using scales = "free_x" adds x axes to each plot:

ggplot(diamonds, aes(carat)) + 
    geom_density() + 
    facet_wrap(~cut, scales = "free_x")

plot with x axes

However, as you can see and the syntax suggests, it also frees the limits of each plot to adjust automatically, so if you want them all to be consistent, you'll need to set them with xlim, lims or scale_x_continuous:

ggplot(diamonds, aes(carat)) + 
    geom_density() + 
    xlim(range(diamonds$carat)) + 
    # or lims(x = range(diamonds$carat))    
    # or scale_x_continuous(limits = range(diamonds$carat))
    facet_wrap(~cut, scales = "free_x")

plot with uniform x axes

like image 123
alistaire Avatar answered Nov 12 '22 20:11

alistaire