Table of Contents
In ggplot2, you can change the font size of text elements in a plot by using the theme function. This can be done by setting the base_size argument to a numerical value, which will represent the font size in points. You can also specify the family of the font by setting the font argument. If you want to use a specific font, you can set the font argument to the name of the font you want to use. In addition, you can also use the theme_bw() function to set the default font size and font type.
You can use the following syntax to change the font size of various elements in ggplot2:
p + theme(text=element_text(size=20), #change font size of all text axis.text=element_text(size=20), #change font size of axis text axis.title=element_text(size=20), #change font size of axis titles plot.title=element_text(size=20), #change font size of plot title legend.text=element_text(size=20), #change font size of legend text legend.title=element_text(size=20)) #change font size of legend title
The following examples show how to use this syntax with the following scatterplot in ggplot2:
library(ggplot2) #create data frame df <- data.frame(x=c(1, 2, 3, 4, 5, 6), y=c(6, 8, 14, 19, 22, 18), z=c('A', 'A', 'B', 'B', 'C', 'C')) #create scatterplot p <- ggplot(df, aes(x=x, y=y, color=z)) + geom_point(size=3) + ggtitle("This is the Title") p
Example 1: Change Font Size of All Text
The following code shows how to change the font size of all text elements in the plot:
p + theme(text=element_text(size=20))
Example 2: Change Font Size of Axis Text
The following code shows how to change the font size of just the axis text:
p + theme(axis.text=element_text(size=30))
Example 3: Change Font Size of Axis Titles
The following code shows how to change the font size of just the axis titles:
p + theme(axis.title=element_text(size=30))
Example 4: Change Font Size of Plot Title
The following code shows how to change the font size of just the plot title:
p + theme(plot.title=element_text(size=30))
Example 5: Change Font Size of Legend Text
The following code shows how to change the font size of just the legend text:
p + theme(legend.text=element_text(size=30))
Example 6: Change Font Size of Legend Title
The following code shows how to change the font size of just the legend title:
p + theme(legend.title=element_text(size=30))