Swap key and label in ggplot legend

Viewed 104

I have a plot like this:

library("ggplot2")
library("ggtext")

df = data.frame(x = rnorm(n=12), y = rnorm(n=12),
                groupshape = rep(c("a","b","c"), 4),
                groupcol = rep(c("e","d","f"), 4))

p = ggplot(df, aes(x = x,y = y, 
               shape = groupshape, 
               color = groupcol)) + 
  geom_point() + theme_classic() + labs(shape = "shape", color = "color")

Producing a plot like this:

Boring Scatterplot

But I want to know how to get something like this with the legend:

Super Cool Scatterplot

How would I do that? I can get rid of the shape itself through guides by turning them all while, but then the text just hovers menacingly without alignment to the legend below.

1 Answers

This could be achieved via the label.position and the label.theme arguments of guide_legend:

library("ggplot2")
library("ggtext")

df = data.frame(x = rnorm(n=12), y = rnorm(n=12),
                groupshape = rep(c("a","b","c"), 4),
                groupcol = rep(c("e","d","f"), 4))

ggplot(df, aes(x = x,y = y, 
                   shape = groupshape, 
                   color = groupcol)) + 
  geom_point() + theme_classic() + labs(shape = "shape", color = "color") +
  guides(color = guide_legend(label.position = "left", label.theme = element_text(face = "bold")),
         shape = guide_legend(label.position = "left"))

Related