R:在 R 中添加图例
R: adding a plot legend in R
plot(iris$Sepal.Length, iris$Sepal.Width, col = iris$Species)
我知道我可以使用 legend()
函数手动设置我的图例。但是,我不知道为我的数据中的不同物种分配了哪种颜色?有没有自动获取 plot()
添加图例的方法?
正如@rawr 所说,palette()
决定了使用的颜色顺序。如果您使用整数指定颜色,它还会查看 palette()
。于是
with(iris,plot(Sepal.Length, Sepal.Width, col = Species))
legend("topright",legend=levels(iris$Species),col=1:3, pch=1)
效果很好。
Base R 没有自动图例功能:ggplot2
包有。
library(ggplot2)
ggplot(iris,aes(Sepal.Length,Sepal.Width,colour=Species))+geom_point()
为您提供带有自动图例的图(如果您不喜欢灰色背景,请使用 theme_set(theme_bw())
)。
内置的lattice
包也可以做自动图例:
library(lattice)
xyplot(Sepal.Width~Sepal.Length,group=Species,data=iris,auto.key=TRUE)
plot(iris$Sepal.Length, iris$Sepal.Width, col = iris$Species)
我知道我可以使用 legend()
函数手动设置我的图例。但是,我不知道为我的数据中的不同物种分配了哪种颜色?有没有自动获取 plot()
添加图例的方法?
正如@rawr 所说,palette()
决定了使用的颜色顺序。如果您使用整数指定颜色,它还会查看 palette()
。于是
with(iris,plot(Sepal.Length, Sepal.Width, col = Species))
legend("topright",legend=levels(iris$Species),col=1:3, pch=1)
效果很好。
Base R 没有自动图例功能:ggplot2
包有。
library(ggplot2)
ggplot(iris,aes(Sepal.Length,Sepal.Width,colour=Species))+geom_point()
为您提供带有自动图例的图(如果您不喜欢灰色背景,请使用 theme_set(theme_bw())
)。
内置的lattice
包也可以做自动图例:
library(lattice)
xyplot(Sepal.Width~Sepal.Length,group=Species,data=iris,auto.key=TRUE)