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?
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.
You can use the following syntax to change the legend labels in ggplot2: p + scale_fill_discrete(labels=c('label1', 'label2', 'label3', ...))
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.
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.
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))
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With