Search code examples
rggplot2themesscale

discrete scale: axis text and axis title on different sides


Is it possible to have the axis title and the axis text on two different sides in a ggplot with a discrete scale. With scale_y_discrete(position="left") I get both on the left side with scale_y_discrete(position="right") I get both on the right side. I would like to have the axis text with the factor levels on the left side and the axis title with the variable name on the right side. (This works best with plots aligned with patchwork in my case)

I think with continuous scales I could do the same with a secondary axis and then hiding the left or right axis title respectively.


Solution

  • There are various ways to achieve this effect, but your secondary axis idea is probably the best, so here's a worked example using a continuous axis.

    library(ggplot2)
    
    ggplot(iris, aes(Sepal.Length, as.numeric(Species), group = Species)) +
      geom_violin() +
      scale_y_continuous(NULL, labels = ~levels(iris$Species)[.x], 
                         breaks = seq_along(levels(iris$Species)),
                         sec.axis = sec_axis(~.x, "Species")) +
      theme(axis.ticks.y.right = element_blank(),
            axis.text.y.right = element_blank())
    

    enter image description here