Reputation: 1600
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"))
It's a point of detail but a coauthor insisted on it.
Upvotes: 5
Views: 3000
Reputation: 69171
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)
Upvotes: 5