本文介绍了R图中未显示的图例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在与R.合作,我绘制了以下曲线图:

#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")

我正在尝试为所有这些情节添加图例:

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)

但是这些传说都没有出现。有人知道为什么这些传说行不通吗?我知道在gglot中如何做到这一点,但它不能与R中的基础图一起工作。我在这里遵循这个网站的说明:http://www.sthda.com/english/wiki/add-legends-to-plots-in-r-software-the-easiest-way。有没有人能教我怎么修这个?

谢谢

推荐答案

legend位置在ylim之外,即默认情况下,ylim是根据min/max值计算的,更改ylim就会出现。即当前ylim在0,35,而为y轴指定的位置是95(差异巨大)

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)

-输出

这篇关于R图中未显示的图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-19 00:14