Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

r ggplot2: varying font sizes in legend

I have two lines in my legend. How can I make one line bold, colour blue and large font and one line with small fonts, colour red and in italics?

library(ggplot2)
library(gridExtra)
p <- qplot(data = mtcars, wt, mpg)
print(arrangeGrob(p, legend = 
  textGrob("large font size colour blue bold\n small font size colour red italic", 
           rot = -90, vjust = 1)))

Thank you for your help.

like image 211
adam.888 Avatar asked Jan 11 '15 11:01

adam.888


People also ask

How do I change the font 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.

How do I make the legend text bigger in ggplot2?

How can I change the default font size in ggplot2? Set base_size in the theme you're using, which is theme_gray() by default. The base font size is 11 pts by default. You can change it with the base_size argument in the theme you're using.

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', ...))


2 Answers

You need to split your text into two textGrobs:

library(ggplot2)
library(gridExtra)
p <- qplot(data = mtcars, wt, mpg)
t1 <- textGrob("small font size colour red italic",
               gp = gpar(fontsize = 12, col = 'red', fontface = 'italic'), 
               rot = -90, vjust = 1)
t2 <- textGrob("large font size colour blue bold", 
               gp = gpar(fontsize = 20, col = 'blue', fontface = 'bold'), 
               rot = -90, vjust = 1)
print(arrangeGrob(p, t1, t2, widths = c(9/10, 1/20, 1/20), nrow = 1))

enter image description here

like image 185
tonytonov Avatar answered Oct 13 '22 11:10

tonytonov


A solution using expression and atop:

p <- qplot(data = mtcars, wt, mpg)
print(arrangeGrob(p, legend=
      textGrob(expression(atop("large font size colour blue bold\n", atop(italic("small font size colour red italic")))),
      rot = -90, vjust = 1, gp=gpar(fontsize=16,fontface="bold"))))

enter image description here

like image 26
Jaap Avatar answered Oct 13 '22 11:10

Jaap