Open In App

Change Legend Size in Base R Plot

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will be looking at the approach to change the size of the legend in the plot in the R programming language.

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.

Syntax: legend(x, y, legend, fill, col, bg, lty, cex, title, text.font, bg)

Parameters:

  • x and y: These are co-ordinates to be used to position the legend
  • legend: Text of the legend
  • fill: Colors to use for filling the boxes with legend text
  • col: Colors of lines
  • bg: It defines background color for the legend box
  • cex: Used for scaling
  • title: Legend title        (optional)
  • text.font: An integer specifying the font style of the legend (optional)

Returns: Legend plot

cex is a number indicating the amount by which plotting text and symbols should be scaled relative to the default. 1=default, 1.5 is 50% larger, 0.5 is 50% smaller, etc. 

Example 1:

R




x1 <- c(1,8,5,3,8,7)                
y1 <- c(4,6,3,8,2,7)
plot(x1,y1,cex=.8,pch=1,col="red")
  
x2<-c(4,5,8,6,4)
y2<-c(9,8,2,3,1)
  
x3<-c(2,1,6,7,4)
y3<-c(7,9,1,5,2)
  
points(x2,y2,cex=.8,pch=2,col="blue")
points(x3,y3,cex=.8,pch=3,col="green")
  
legend("topright",c("gfg1","gfg2","gfg3"),
       cex=0.5,col=c("red","blue","green"),
       pch=c(1,2,3))


Output:

Example 2:

R




gfg_data <- matrix(c(1,2,3,4,5,6,7,8,9,10), ncol = 5)
  
colnames(gfg_data) <- paste0("Gfg", 1:5)
rownames(gfg_data) <- c('A','B')
  
gfg_data      
  
barplot(gfg_data,                   
        col = 1:nrow(gfg_data))
  
legend("topright",
       legend = rownames(gfg_data),
       pch = 15,
       col = 1:nrow(gfg_data),cex=2.5)


Output:



Last Updated : 30 May, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads