Alignment of legend, when bottom-placed

Given the example code below, how do I control alignment of legend when bottom-placed? E.g. left-aligned?

# Load libraries ----------------------------------------------------------
library("tidyverse")

# Define data -------------------------------------------------------------
d = tribble(
  ~x, ~lbl, ~cat,
  1, "This is one value in the dataset we are working with", "This is one category",
  2, "This is another", "This is another",
  3, "This is yet another", "This is yet another",
  4, "And just one more", "And just one more",
  5, "Then the last one right here", "Then the last one right here, concluding all the categories"
)

# Do visualisation --------------------------------------------------------
d %>% 
  ggplot(aes(x = x, y = lbl, colour = cat)) +
  geom_point() +
  theme(legend.position = "bottom") +
  labs(y = "") +
  guides(colour = guide_legend(nrow = 2, byrow = TRUE))

legend.position will take only a single character string argument, but will take a two-element vector argument. Takes a fair amount of tweaking to place it where you want to, and winds up differently depending on the rendering engine. I also had to put the legend on a single row.

library("tidyverse")

# Define data -------------------------------------------------------------
d = tribble(
  ~x, ~lbl, ~cat,
  1, "This is one value in the dataset we are working with", "This is one category",
  2, "This is another", "This is another",
  3, "This is yet another", "This is yet another",
  4, "And just one more", "And just one more",
  5, "Then the last one right here", "Then the last one right here, concluding all the categories"
)

# Do visualisation --------------------------------------------------------
d %>% 
  ggplot(aes(x = x, y = lbl, colour = cat)) +
  geom_point() +
  theme(legend.position = c(.25,-0.03575)) +
  labs(y = "") +
  guides(colour = guide_legend(nrow = 1, byrow = TRUE))

Created on 2020-03-28 by the reprex package (v0.3.0)

Close @technocrat, but note entirely there - It has to be 2 rows and the entire legend should be visible?

Basically, given my plot, I just want to left-align the bottom-legend?

1 Like

Options are left margin, top margin, bottom margin, right margin, all centered, as far as I can tell. Pick one. Or c(x,y) within the viewport. You might try expanding the panel margins to make room for two rows. See the arguments to theme

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.