Home > Back-end >  How to change the width of plot legend box in R
How to change the width of plot legend box in R

Time:09-26

I want to make my legend box width look like the one on the left, but instead, I got the one on the right. I couldn't figure it out. I'm new in R, what function do I need to use? enter image description here

CodePudding user response:

You can use the text.width argument of the legend()-function.

Example with dummy data

data <- as.matrix(data.frame(A = c(0.2, 0.4),      
                             B = c(0.3, 0.1),
                             C = c(0.7, 0.1),
                             D = c(0.1, 0.2),
                             E = c(0.3, 0.3)))

barplot(data, col = c("#1b98e0", "#353436"))
legend("topleft",                                   
       legend = c("Group 1", "Group 2"),
       fill = c("#1b98e0", "#353436"),
       text.width = 2)

which yields

stacked bar chart with wide legend

  • Related