Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to align legend symbol with wrapped legend text on ggplot2

Tags:

Is there a way to align the legend symbol (red, green or blue dot) with the first line of the wrapped legend text on this example plot? (taken from eipi10 Multiple Lines for Text per Legend Label in ggplot2)

library(stringr)
library(tidyverse)

# Create long labels to be wrapped
iris$Species = paste(iris$Species, 
                     "random text to make the labels much much longer than the original labels")

ggplot(iris, aes(Sepal.Length, Sepal.Width, colour=str_wrap(Species,20))) +
  geom_point() +
  labs(colour="Long title shortened\nwith wrapping") +
  theme(legend.key.height=unit(2, "cm"))

Plot with wrapped legend text

It's a point of detail but a coauthor insisted on it.

like image 523
Nakx Avatar asked Jan 29 '19 01:01

Nakx


1 Answers

Here's one solution that is sort of a hack by changing the background color to white and using vjust. I couldn't find an easy way to top-align the point within the box...

library(stringr)
library(tidyverse)
# Create long labels to be wrapped
iris$Species = paste(iris$Species, 
                     "random text to make the labels much much longer than the original labels")

ggplot(iris, aes(Sepal.Length, Sepal.Width, colour=str_wrap(Species,20))) +
  geom_point() +
  labs(colour="Long title shortened\nwith wrapping") +
    theme(legend.key.height=unit(2, "cm"), legend.key = element_rect(fill = "white")) +
  guides(colour = guide_legend(label.vjust = -1, label.position = "right"))

Created on 2019-01-28 by the reprex package (v0.2.1)

like image 175
Chase Avatar answered Sep 20 '22 09:09

Chase