简体   繁体   English

我如何在 R 中修复 plot 中的图例

[英]How I fix the legend in a plot in R

I run the following code:我运行以下代码:

plot(1:3, rnorm(3), pch = 1, lty = 1, type = "o", ylim=c(-2,2))
lines(1:3, rnorm(3), pch = 2, lty = 2, type="o")
legend(1,-1,c("group A", "group B"), pch = c(1,2), lty = c(1,2))

But the result I get is the following:但我得到的结果如下:

wrong legend错误的传说

How can I fix the legend?我该如何修复传说?

You gave the legend position as x=1, y=-1, in events that the points or lines are in that region it fails.您将图例 position 指定为 x=1,y=-1,如果点或线位于该区域中,则它会失败。

You have a few choices, either set the legend to top right, or you have to rescale you ylim in your case, sorry i don't have your seed so I cannot reproduce the plot.你有几个选择,要么将图例设置在右上角,要么在你的情况下重新调整你的 ylim,对不起,我没有你的种子,所以我无法重现 plot。 Or you can use the default "topleft","topright":或者你可以使用默认的“topleft”,“topright”:

set.seed(100)
plot(1:3, rnorm(3), pch = 1, lty = 1, type = "o", ylim=c(-2,2))
lines(1:3, rnorm(3), pch = 2, lty = 2, type="o")
#legend(2.3,1.5,c("group A", "group B"), pch = c(1,2), lty = c(1,2))
legend("topleft",c("group A", "group B"), pch = c(1,2), lty = c(1,2))

This is the output I get这是我得到的 output

You need a legend out of the plot because your generating new plot after each run, use this您需要 plot 中的图例,因为您在每次运行后生成新的 plot,请使用此

 plot(1:3, rnorm(3), pch = 1, lty = 1, type = "o", ylim=c(-2,2))
 lines(1:3, rnorm(3), pch = 2, lty = 2, type="o")
 legend("bottomright",c("group A", "group B"), pch = c(1,2), lty = c(1,2), inset=c(0,1), xpd=TRUE, horiz=TRUE, bty="n")

Here is the output这是 output

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM