I have a figure with a legend. I want the legend on the right with the legend title on the right of the legend. I also want the legend in the middle of the page.
Okay, first without a title.
# Load library
library(ggplot2)
# Plot data without title
ggplot(iris) +
geom_point(aes(x = Sepal.Length, y = Sepal.Width, fill = Species), shape = 21) +
theme(legend.title = element_text(angle = -90)) +
guides(fill = guide_legend(title.position = "right",
title = ""))
Perfect! Now, just to add the title...
# Plot data
ggplot(iris) +
geom_point(aes(x = Sepal.Length, y = Sepal.Width, fill = Species), shape = 21) +
theme(legend.title = element_text(angle = -90)) +
guides(fill = guide_legend(title.position = "right",
title = "This is the species... Yup, defo the species"))
Hmmm. The legend is not centred relative to the title and page, so I use legend.title.align
to try and rectify it.
# Attempted solutions
#1) legend.title.align
ggplot(iris) +
geom_point(aes(x = Sepal.Length, y = Sepal.Width, fill = Species), shape = 21) +
theme(legend.title = element_text(angle = -90), legend.title.align = 0.5) + # 0.5 should be in the middle
guides(fill = guide_legend(title.position = "right",
title = "This is the species... Yup, defo the species"))
No dice. Next try: title.vjust
to vertically adjust the title.
#2) vjust
ggplot(iris) +
geom_point(aes(x = Sepal.Length, y = Sepal.Width, fill = Species), shape = 21) +
theme(legend.title = element_text(angle = -90)) +
guides(fill = guide_legend(title.position = "right",
title = "This is the species... Yup, defo the species",
title.vjust = 0.5)) # Vertical adjustment in figure
Not the solution either. Perhaps vjust
and hjust
are relative to the reading direction? So, let's try title.hjust
...
#3) hjust - Perhaps it's relative to the direction of reading?
ggplot(iris) +
geom_point(aes(x = Sepal.Length, y = Sepal.Width, fill = Species), shape = 21) +
theme(legend.title = element_text(angle = -90)) +
guides(fill = guide_legend(title.position = "right",
title = "This is the species... Yup, defo the species",
title.hjust = 0.5)) # Horizontal adjustment... relative to reading direction?
That doesn't work either. Finally, perhaps vjust
and hjust
in element_text
that defines legend_title
are the correct parameters...
#4) v/hjust in element_text
ggplot(iris) +
geom_point(aes(x = Sepal.Length, y = Sepal.Width, fill = Species), shape = 21) +
theme(legend.title = element_text(angle = -90, hjust = 0.5, vjust = 0.5)) +
guides(fill = guide_legend(title.position = "right",
title = "This is the species... Yup, defo the species"))
Created on 2019-10-21 by the reprex package (v0.3.0)
Nope. I'm sure this is straightforward and there are an abundance of somewhat similar solutions, yet I cannot find anything that works. Can someone explain my daft mistake?