Search code examples
rggplot2alignmentlegend

Aligning the keys legend and labels to the right side of the legend box, in ggplot2


I have the following data frame where I predict y as a function of age and gender:

df = data.frame(
  age = c('old', 'old', 'young', 'young'),
  gender = c('male', 'female', 'male', 'female'),
  y = 1:4)

and the corresponding graph:

ggplot(df, aes(x=age, y=y, fill = gender)) + 
  geom_col(position = 'dodge')

enter image description here

I would like to control the appearance of the legend box. In particular, I would like the entire box to be aligned to the right (and not to the left). So, the key legend should appear on the right side of the box, and left to it should be the labels.

I know the legend.text.align argument of the theme() function but it controls only the distance between a keys and its the corresponding label.

Any idea of how to reverse to alignment?


Solution

  • You can use guide_legend(label.position = ... to adjust the label position, labels etc.

    ggplot(df, aes(x=age, y=y, fill = gender)) + 
      geom_col(position = 'dodge') +
      guides(fill = guide_legend(# title.hjust = 1, # adjust title if needed
                                 label.position = "left",
                                 label.hjust = 1)
    

    enter image description here

    For more info: https://ggplot2.tidyverse.org/reference/guide_legend.html