Skip to content
Related Articles

Related Articles

Improve Article

Change Font of Plot in R

  • Last Updated : 06 Jun, 2021

In this article, we will be looking at the two different approaches to change the font of the plot in R programming language.

Method 1: Using windowsFont() function and family argument 

In this approach to change the font of the given plot, the user needs to call the windowsFont() which is one of the in-build function of the R programming language, with the name of the font as its parameter, this function is used to specify the font family as per requirement and with this, the user also need to use the family argument of the plot() function to change the font family of the texts of the plot in the R programming language.

 windowsFont() function is used to handle the translation of a device-independent R graphics font family name to a Windows font description and is available only on Windows.

Syntax:

windowsFont(family)



Parameter:

  • family: a character vector containing the font family name (“TT” as the first two characters indicate a TrueType font).

Example:

R




sample1_x <- c(1, 8, 5, 3, 8, 7)                
sample1_y <- c(4, 6, 3, 8, 2, 7)
  
windowsFonts(A = windowsFont("Rockwell"))  
  
plot(sample1_x, sample1_y, family = "A", cex=.8, pch=1, 
     col="red", main="Plot to show font Change")
  
sample2_x<-c(4, 5, 8, 6, 4)
sample2_y<-c(9, 8, 2, 3, 1)
sample3_x<-c(2, 1, 6, 7, 4)
sample3_y<-c(7, 9, 1, 5, 2)
  
points(sample2_x, sample2_y, cex=.8, pch=2, col="blue")
points(sample3_x, sample3_y, cex=.8, pch=3, col="green")
  
legend("topright", c("gfg1", "gfg2", "gfg3"),
       cex=1, col=c("red", "blue", "green"), pch=c(1, 2, 3))

Output:

Method 2: Using windowsFont() and theme() function from ggplot2 

In this method to change the font of the given plot user firstly needs to install and import the ggplot2 package and then call the windowsFont() function to specify the required parameter as its parameter and secondly need to call the theme() function from the ggplot2 package to change the font of the given ggplot2 plot.

theme() function used to modify theme settings.

Syntax:

theme(…, complete = FALSE, validate = TRUE)

Parameters:

  • …: a list of element names, element pairings that modify the existing theme.
  • complete: set this to TRUE if this is a complete theme, such as the one returned by theme_grey().
  • validate: TRUE to run validate_element, FALSE to bypass checks.

Example:

R




library("ggplot2")   
  
gfg_data<-data.frame(x_values=c(1, 2, 3, 4, 5), y_values=c(5, 4, 3, 2, 1))
  
windowsFonts(A = windowsFont("Times New Roman"))  
  
gfg_plot<-ggplot(data=gfg_data, aes(x_values, y_values)) +
  geom_bar(stat="identity")+ ggtitle("Plot to show font change")+
  theme(text = element_text(family = "A"))
  
gfg_plot

Output:




My Personal Notes arrow_drop_up
Recommended Articles
Page :