Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adjust position and font size of legend title in ggplot2

Tags:

r

ggplot2

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?

like image 308
Paul M Avatar asked Mar 09 '12 18:03

Paul M


People also ask

How do I change the title size in legend?

To set a legend with title, we use legend() method with labels and title arguments. Then we get the legend title, by using the get_title() function. To change the font size of legend's title, we use set_fontsize() method and set it to x-large.

How do I change the legend text in ggplot2?

You can use the following syntax to change the legend labels in ggplot2: p + scale_fill_discrete(labels=c('label1', 'label2', 'label3', ...))

How do I change the title of a legend in ggplot2?

Method 1: Change Legend Title using guides() Function. Now if we want to change Legend Title then we have to add guides and guide_legend functions to the geom_point function. Inside guides() function, we take parameter named 'color' because we use color parameter for legend in ggplot() function.

How do I change the text size in legend in R?

To change the legend size of the plot, the user needs to use the cex argument of the legend function and specify its value with the user requirement, the values of cex greater than 1 will increase the legend size in the plot and the value of cex less than 1 will decrease the size of the legend in the plot.


2 Answers

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)) 
like image 181
Amm Avatar answered Sep 25 '22 01:09

Amm


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.

like image 25
joran Avatar answered Sep 24 '22 01:09

joran