0

I am trying to make a plot with the legend at the bottom. I would like to get one line per scale i.e., one line with am and one line with vs (just like it displays if we use theme(legend.position = "left") in the code below).

This might be very simple but I was not able to find the correct keywords or to understand correctly tutorials. Should it be done using theme() or guides()?

Thanks for advices or links towards the solution!

Here is an reprex:

This code has the legend at the bottom, as expected, but I can't figure out how to have one line per scale (here color and shape):

library(ggplot2)

ggplot(data = mtcars, aes(x = disp, y = hp, color = as.factor(vs), shape = as.factor(am))) +
  geom_point() +
  scale_color_discrete(name = "vs") +
  scale_shape_discrete(name = "am") +
  guides(shape = guide_legend(title.position = "left", order = 1, nrow = 1),
         color = guide_legend(title.position = "left", order = 2, nrow = 1)) +
  theme(legend.position = "bottom")

When using legend.position = "left" (or right), there is one line per scale:

library(ggplot2)

ggplot(data = mtcars, aes(x = disp, y = hp, color = as.factor(vs), shape = as.factor(am))) +
  geom_point() +
  scale_color_discrete(name = "vs") +
  scale_shape_discrete(name = "am") +
  guides(shape = guide_legend(title.position = "left", order = 1, nrow = 1),
         color = guide_legend(title.position = "left", order = 2, nrow = 1)) +
  theme(legend.position = "left")

Created on 2021-06-14 by the reprex package (v2.0.0)

Paul
  • 2,850
  • 1
  • 12
  • 37

1 Answers1

0

Well, looking around I found this post that solved the question by adding legend.box="vertical" argument to theme().

Note: it seems that default arrangement of multiple legends has changed during ggplot2 history; I found older posts like this one where vertical arrangement with legend on top seems to be the default.

library(ggplot2)

ggplot(data = mtcars, aes(x = disp, y = hp, color = as.factor(vs), shape = as.factor(am))) +
  geom_point() +
  scale_color_discrete(name = "vs") +
  scale_shape_discrete(name = "am") +
  guides(shape = guide_legend(title.position = "left", order = 1, nrow = 1),
         color = guide_legend(title.position = "left", order = 2, nrow = 1)) +
  theme(legend.position = "bottom",
        legend.box="vertical")

Created on 2021-06-14 by the reprex package (v2.0.0)

Paul
  • 2,850
  • 1
  • 12
  • 37