adding a legend to a barplot at he top left

Viewed 47
barcols <- c("green","red","purple")
barcols


barplot(table(gender$Alert.Level, gender$Gender),las=1, beside= TRUE, ylab= "Frequency", xlab="gender", cex.names=0.7, main="Frequency of violations by gender" , col=barcols)

How would you go about adding a legend to the top left where green= alert level 1, red = alert level 2 and purple = alert level 3

enter image description here

1 Answers

Here are two plots, one with a vertical legend and the other with a horizontal legend.

Note that in the first plot the y axis limits are extended in order to have the legend not overplot the bars.

set.seed(2022)
al <- c("alert level 1", "alert level 2", "alert level 3")
al <- factor(al, levels = al)
gender <- data.frame(Alert.Level = sample(al, 100, TRUE),
                     Gender = sample(c("Female", "Male", "Unknown"), 100, TRUE))

barcols <- c("green","red","purple")

barplot(
  table(gender$Alert.Level, gender$Gender),
  las=1, beside = TRUE, 
  #
  ylim = c(0, 17),
  #
  ylab= "Frequency", xlab="gender", 
  cex.names=0.7, 
  main="Frequency of violations by gender", 
  col = barcols
)
lgd <- sort(unique(gender$Alert.Level))
legend("topleft", legend = lgd, fill = barcols)

barplot(
  table(gender$Alert.Level, gender$Gender),
  las=1, beside= TRUE, 
  #
  ylim = c(0, 17),
  #
  ylab= "Frequency", xlab="gender", 
  cex.names=0.7, 
  main="Frequency of violations by gender", 
  col = barcols
)
legend("topleft", legend = lgd, fill = barcols, horiz = TRUE)

Created on 2022-03-23 by the reprex package (v2.0.1)

Related