简体   繁体   English

如何在 R 中为绘图添加图例

[英]How to add a legend to a plot in R

I´m new to R. I cannot put a legend in a plot chart, there is someting wrong with my code, I´ve tried to put a legend on this plot.我是 R 的新手。我不能在图表中放置图例,我的代码有问题,我试图在这个图上放置图例。 I did a hash to put some colors on my model, but now I can´t figure out how to put the correct legend on it.我做了一个散列,在我的模型上放了一些颜色,但现在我不知道如何在它上面放正确的图例。 This is what I di:这就是我所做的:

myhash<-c(a="green",b="pink",c="blue",d="purple",e="orange",f="brown",g="yellow",
          h="black",i="gray") 
mycolor<-myhash[df$category]
plot(df$growth,df$tannin,col=mycolor,cex=1,pch=16,xlab="Crecimiento",ylab="Taninos", main = "Modelo lineal Taninos vs Crecimiento")

I tried to put the legend like this :我试着把这个传说放在这样的地方:

legend("topright",c(df$tannin),fill=c("green","pink","blue","purple","orange","brown","yellow",
          "black","gray"))

Please let me know how can I fix it, Im very beginner in R. Also, I cannot use any library.请让我知道如何修复它,我是 R 的初学者。另外,我不能使用任何库。 Thanks in advance.提前致谢。

The problem seems to be that there is no legend (the argument to function legend , not the function) to show as text beside the fill colors.问题似乎是没有图例(函数legend的参数,而不是函数)在填充颜色旁边显示为文本。
To use a named argument, legend = unique(names(mycolor)) solves the problem.要使用命名参数, legend = unique(names(mycolor))解决了这个问题。

set.seed(2020)
df <- data.frame(category = rep(c("a","b", "c", "d"), 4),
                 growth = 1:16, tannin = cumsum(rnorm(16)))

myhash <- c(a = "green", b = "pink", c = "blue", d = "purple") 
mycolor <- myhash[df$category]

plot(df$growth, df$tannin, col = mycolor, cex = 1, pch = 16,
     xlab = "Crecimiento", ylab = "Taninos", 
     main = "Modelo lineal Taninos vs Crecimiento")

legend("topright", legend = unique(names(mycolor)), fill = mycolor)

在此处输入图片说明

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

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