3

I am working with R. I made the following plots:

#create data
a = abs(rnorm(100,10,10))
b = abs(rnorm(100,10,10))
i = 1
c = data.frame(a,b,i)
c$col = as.factor(ifelse(c$b>10,"red", "blue"))

a = abs(rnorm(100,10,10))
b = abs(rnorm(100,10,10))
i = 2
d = data.frame(a,b,i)
d$col = as.factor(ifelse(d$a>10,"red", "blue"))

a = abs(rnorm(100,10,10))
b = abs(rnorm(100,10,10))
i = 3
e = data.frame(a,b,i)
e$col = as.factor(ifelse(e$b>10,"red", "blue"))




#create data
a = abs(rnorm(100,10,10))
b = abs(rnorm(100,10,10))
i = 1
c = data.frame(a,b,i)
c$col = as.factor(ifelse(c$b>10,"red", "blue"))

plot_1 = plot(c$a, type = "h", col = c$col, main = "plot_1, i = 1")



plot_2 = plot(d$a, type = "h", col = d$col, main = "plot_2, i = 2")



plot_3 = plot(e$a, type = "h", col = e$col, main = "plot_3, i = 3")

enter image description here

I am trying to add legends to all of these plots:

plot_1 = plot(c$a, type = "h", col = c$col, main = "plot_1, i = 1")


legend(1, 95, legend=c("Sampled", "Not Sampled"),
       col=c("red", "black"), lty=1:2, cex=0.8)

plot_2 = plot(d$a, type = "h", col = d$col, main = "plot_2, i = 2")

legend(1, 95, legend=c("Sampled", "Not Sampled"),
       col=c("red", "black"), lty=1:2, cex=0.8)

plot_3 = plot(e$a, type = "h", col = e$col, main = "plot_3, i = 3")

legend(1, 95, legend=c("Sampled", "Not Sampled"),
       col=c("red", "black"), lty=1:2, cex=0.8)

But none of these legends are showing up. Does anyone know why these legends are not working? I know how to do this in ggplot, but it is not working with the base plots in R. I am following the instructions from this website here: http://www.sthda.com/english/wiki/add-legends-to-plots-in-r-software-the-easiest-way. Can someone please show me how to fix this?

Thanks

stats_noob
  • 5,401
  • 4
  • 27
  • 83
  • 1
    Here is an option: `legend("topleft", legend=c("Sampled", "Not Sampled"), col=c("red", "black"), lty=1:2, cex=0.8)` – Dave2e Oct 09 '21 at 19:04

1 Answers1

4

The legend location is outside the ylim i.e. by default, the ylim is calculated based on the min/max values, change the ylim and it appears. i.e. currently the ylim is at 0, 35, whereas the location specified for y axis is 95 (huge difference)

plot(c$a, type = "h", col = c$col, main = "plot_1, i = 1", 
      ylim = c(0, 100))
legend(1, 95, legend=c("Sampled", "Not Sampled"),
        col=c("red", "black"), lty=1:2, cex=0.8)

-output

enter image description here

akrun
  • 874,273
  • 37
  • 540
  • 662
  • 1
    Can i ask you in "next answer" of this post? I can't create a new question because system says that: "You have reached your question limit"? It consdiers a legend too. – manro Oct 09 '21 at 21:41
  • @ manro: what do you mean? – stats_noob Oct 09 '21 at 23:06