How to make legend in R?

2019-08-01 03:47发布

问题:

I have data that falls into one of many categories. Here is a very simplified version of what I'm doing to my data. I want to make a scatterplot where different colors represent different categories. However, there are many different categories so instead of manually choosing the colors, I'm letting R choose for me by setting col=data$category within the plot function. However, I can't figure out how to generate a legend -- every parameter that I put inside the legend function never actually generates anything. Can someone help?

data <- data.frame(rnorm(50),sample(1:10,50,replace=TRUE))
colnames(data) <- c("data", "category")
plot(data$data, col=data$category)
legend("topright", data$category)

回答1:

Try something like this,

legend("topright", legend=unique(data$category), pch=1, col=unique(data$category))


标签: r legend