R – Using coord_flip() with facet_wrap(scales = “free_y”) in ggplot2 seems to give unexpected facet axis tick marks and tick labels

ggplot2r

I am trying to create a faceted plot with flipped co-ordinates where one and only one of the axes are allowed to vary for each facet:

require(ggplot2)
p <- qplot(displ, hwy, data = mpg)
p + facet_wrap(~ cyl, scales = "free_y") + coord_flip()

enter image description here

This plot is not satisfactory to me because the wrong tick marks and tick labels are repeated for each plot. I want tick marks on every horizontal axis not on every vertical axis.

This is unexpected behaviour because the plot implies that the horizontal axis tick marks are the same for the top panels as they are for the bottom ones, but they are not. To see this run:

p <- qplot(displ, hwy, data = mpg)
p + facet_wrap(~ cyl, scales = "fixed") + coord_flip()

So my question is: is there a way to remove the vertical axis tick marks for the right facets and add horizontal axis tick marks and labels to the top facets?

As Paul insightfully points out below, the example I gave can be addressed by swapping x and y in qplot() and avoiding coord_flip(), however this does not work for all geoms for example, if I want a horizontal faceted bar plot with free horizontal axes I could run:

c <- ggplot(diamonds, aes(clarity, fill=cut)) + geom_bar()
c + facet_wrap(~cut, scales = "free_y") + coord_flip()

image

These facets have a variable horizontal axes but repeated vertical axis tick marks instead of repeated horizontal axes tick marks. I do not think Paul's trick will work here, because unlike scatter plots, bar plots are not rotationally symmetric.

I would be very interested to hear any partial or complete solutions.

Best Answer

Using coord_flip in conjunction with facet_wrap is the problem. First you define a certain axis to be free (the x axis) and then you swap the axis, making the y axis free. Right now this is not reproduced well in ggplot2.

In your first example, I would recommend not using coord_flip, but just swapping the variables around in your call to qplot, and using free_x:

p <- qplot(hwy, displ, data = mpg)
p + facet_wrap(~ cyl, scales = "free_x")

enter image description here

Related Topic