Home > database >  How can I adjust the legend box?
How can I adjust the legend box?

Time:10-22

This is my code:

score <- tapply(exams$writing.score 
                   , list(exams$gender,
                          exams$race.ethnicity
                          )
                   , mean)

plot1 <- barplot(score
                 , beside = TRUE
                 , main = "Comparison of Writing Score"
                 , col = c("red", "lightyellow")
                 , xlab = "Race Ethnicity Group"
                 , ylab = "Average Writing Score"
                 , legend.text = c("Female", "Male")
                 , args.legend = list(x = "topright")
)

enter image description here

As I want to make the box: Female and Male smaller so it does not hide the bar behind. How can I make the legend box smaller? I tried to move it to the top right of the chart, but I do not think it moves.

CodePudding user response:

You could use the argument cex. Here is a reproducible example:

data <- matrix(c(1,2,3,4,5,6,7,8,9,10), ncol = 5)

colnames(data) <- paste0("V", 1:5)
rownames(data) <- c('A','B')

# Normal
barplot(data, col = 1:nrow(data))
legend("topright", legend = rownames(data), pch = 15, col = 1:nrow(data))


# With cex
barplot(data, col = 1:nrow(data))
legend("topright", legend = rownames(data), pch = 15, col = 1:nrow(data), cex = 0.5)

Created on 2022-10-21 with enter image description here

Data

df <- structure(c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), dim = c(2L, 5L), dimnames = list(
    c("Female", "Male"), c("V1", "V2", "V3", "V4", "V5")))

CodePudding user response:

It doesn't move because you already are at the very top. To move the top upwards and let the legend follow, expand ylim.

Also try if you like setting the legend horizontal and remove the bty (boxtype). Don't choose the cex too small.

barplot(score
        , beside=TRUE
        , main="Comparison of Writing Score"
        , col=c("red", "lightyellow")
        , xlab="Race Ethnicity Group"
        , ylab="Average Writing Score"
        , legend.text=c("Female", "Male")
        , args.legend=list(x="topright", cex=.9, horiz=TRUE, bty='n')
        , ylim=c(0, max(score)*1.2)
)

enter image description here

Data:

score <- structure(c(96.8, 95.2, 100, 100, 89.7, 89.2, 81.4, 81, 85.1, 
82), dim = c(2L, 5L), dimnames = list(c("1", "2"), c("A", "B", 
"C", "D", "E")))
  • Related