Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to change the width of plot legend box in R

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][1]

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading