Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add a subtitle and change the font size of ggplot plots in R?

Tags:

r

ggplot2

I tried adding a subtitle using +opts(subtitle="text") but nothing showed up. The main title does work (+opts(title="text")).

I would also like to use a larger font for the axis (labels and coordinates), but I can't tell how to do that.

like image 627
David B Avatar asked Oct 05 '10 14:10

David B


People also ask

How do I change the subtitle size in R?

To change the size of the title and subtitle, we use the size parameter of element_text() function. Here we set the size of the title as 30 and the size of the subtitle as 20. Below is the implementation: R.

How do I change the font size in R plot?

Go to the menu in RStudio and click on Tools and then Global Options. Select the Appearance tab on the left. Again buried in the middle of things is the font size. Change this to 14 or 16 to start with and see what it looks like.

Can you change font in Ggplot?

ggplot allows you to change the font of each part of the figure: you just need to know the correct option to modify in the theme. (For a full list of customizable components of the theme, see this documentation.)

How do you add a title and subtitle in R?

You can use the title function to add a title, a subtitle and the axis labels, separately or at the same time. You can add a title to a base R plot using the title function. This is equivalent to set the argument main of the plot function. The title function also supports adding a subtitle with the sub argument.


2 Answers

theme_get() will show you the "hidden" options that you can use in opts(), post 0.91 it's theme()

Current:

theme(axis.text.x=element_text(size=X)) theme(axis.text.y=element_text(size=X)) 

Pre 0.91:

opts(axis.text.x=theme_text(size=X)) opts(axis.text.y=theme_text(size=X)) 

Change size, to your desired size.

wrt the title, you can use "\n" to move the remaining text to a new line:

Current:

labs(title="text \n more text") 

Pre 0.91:

opts(title="text \n more text")  

ggplot2 doesn't have "subtitle" functionality. But you can use the \n term in any of the labels to drop down a line.

like image 193
Brandon Bertelsen Avatar answered Sep 21 '22 13:09

Brandon Bertelsen


Update: ggplot version 2.2.0 can do subtitles, as demonstrated e.g. in this blog post.

Example:

library(ggplot2) packageVersion("ggplot2")  ## 2.2.0 d <- data.frame(x=1:5,y=1:5) ggplot(d,aes(x,y))+     labs(title="abc",subtitle="def")+     ## default left-aligned: moved them to center alignment     theme(plot.title=element_text(hjust=0.5),           plot.subtitle=element_text(hjust=0.5)) 

enter image description here

like image 42
Ben Bolker Avatar answered Sep 22 '22 13:09

Ben Bolker