Home > Blockchain >  Align legend horizontal ggplot2
Align legend horizontal ggplot2

Time:12-03

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

CodePudding user response:

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

  • Related