23
votes

I am adjusting the font size of ggplot2 labels to make them more readable in large format. This works very well except for the legend title. This is illustrated by the following code:

library(ggplot2)
p <- ggplot(diamonds, aes(carat, price, colour=cut)) + geom_point() +
  xlab("Carat") +
  ylab("Price") +
  opts(legend.position=c(0.85, 0.3)) +
  opts(axis.title.x=theme_text(size=16)) +
  opts(axis.title.y=theme_text(size=16, angle=90)) + 
  opts(plot.title=theme_text(size=20)) +
  opts(legend.text=theme_text(size=14)) +
  opts(legend.title=theme_text(size=14)) +
  opts(title="Diamond Prices")
p

The re-sized legend title is no longer properly aligned in the legend box, but is protruding out to the left. The effect is even worse for longer titles. I have tried defining custom values for the vjust and hjust parameters, but there is no apparent response.

Is there a way to adjust the alignment of a re-sized legend title?

2
For ggplot2 3.0+ onwards please follow @Amm solution.Sumanth Lazarus
If you need to change the legend title: p + guides(fill=guide_legend(title="New Legend Title"))Sumanth Lazarus

2 Answers

16
votes

Yes, using a feature of the new 0.9.0 version, guides:

p + guides(colour = guide_legend(title.hjust = 0.5))

You can read about guides here.

34
votes

If you are using ggplot 0.9.1 version, this works for changing the position and size of the legend title

p + theme(legend.position=c(0.85, 0.3),legend.title=element_text(size=14))