rggplot2ggnewscale

Align legend horizontal ggplot2


I am curious as to whether there is a way to stack legends horizontally rather than vertically in ggplot2 and ggnewscale:

Example using mtcars dataset:

ggplot(mtcars, aes(x = mpg, y = cyl)) +
  geom_point(aes(col = gear)) +
  ggnewscale::new_scale_color() +
  geom_point(aes(col = carb))

Plot for example

enter image description here


Solution

  • You can individually control legends via guides(...):

    library(ggnewscale)
    
    ggplot(mtcars, aes(x = mpg, y = cyl)) +
      geom_point(aes(col = gear)) +
      ggnewscale::new_scale_color() +
      geom_point(aes(col = carb))+
      theme(legend.direction = "vertical",
          legend.box = "horizontal",
          legend.position = "right") +
      guides(size=guide_legend(direction='horizontal'))
    

    enter image description here