传说中的颜色有很多组

colors in legend with many groups

我知道这可能是一个简单的问题,但我真的很挣扎..

iris数据集为例,我可以使用下面的代码根据不同的物种进行不同颜色的绘图:

plot(iris$Sepal.Length, iris$Sepal.Width, col=iris$Species)
legend('topright', legend=c("setosa", "virginica", "versicolor"))

但实际上我无法添加与图例调用中使用的相同颜色。

此外,我使用的数据集有几个唯一值。有没有办法在不手动指定的情况下添加颜色?

ggplot 根据 aes 选项中使用的颜色自动添加图例,但我需要对 plot 包做同样的事情。

有没有简单的解决办法?

谢谢

你可以试试这个

plot(Sepal.Width~Sepal.Length, data=iris, col=Species)
legend('topright', legend=levels(iris$Species), col=1:3, pch=1)

您的绘图调用使用与 iris$Species 的值相对应的默认颜色(即 1、2、3,记住它是一个因子,请参阅 as.numeric(iris$Species) 的输出!)

只有少数人 类 简单的解决方案是做类似的事情:

cols <- c("darkgreen", "darkblue", "orange")
plot(iris$Sepal.Length, iris$Sepal.Width, col=cols[iris$Species], pch=20)

legend('topright', legend=levels(iris$Species), 
       col= cols, pch=20)

一个更通用的解决方案是使用调色板,使用 heat.colorsgray.colorsrainbow.colors 等函数,例如

cols <- heat.colors(5) // 5 is the number of colors in the palette

RColorBrewer 包中找到了更多精美的调色板。

此外,colorRampPalette 功能允许您混合这些调色板以获得更平滑的结果。例如:

library(RColorBrewer)
colorRampPalette(brewer.pal(9,"Blues"))(100)