如何使用多边形函数获得密度图?我有多个组要绘制

How can I get density plot with polygon function? I have multiple groups to plot

所以我在R中使用了基础数据,"iris"数据

到目前为止我所做的是创建一个向量,其中 x 值 Sepal.Length 和 y 值与密度函数输出。 然后我绘制了它们,但它并没有像我打算的那样在 3 个不同的组(按物种)中显示。

我的直觉是我的分组有问题...你能帮帮我吗?

<>

x<-iris$Sepal.Length
y<-iris$Species
z<-split(x,y)
x_min <- min(x)
x_max <- max(x)
a <- sapply(z, function(x) density(x,from=x_min,to=x_max))
a
for(i in 1:length(a)){
    polygon(a$x[i],a$y[i])
}

这是输出应该是什么样的

非常感谢

ggplot 使像这样的分组操作变得更加容易,因为您只需将分组变量映射到用于区分组的审美(这里 fill),它会处理颜色和图例你。 (当然,您可以进一步自定义。)

library(ggplot2)

ggplot(iris, aes(Sepal.Length, fill = Species)) + geom_density()

如果你想在基础绘图中这样做,通常最简单的方法是先设置空 window,然后遍历组。由于您需要设置颜色和组,因此 Maplapply 更合适。图例需要额外调用。

plot(x = c(4, 8.5), y = c(0, 1.5), type = "n", 
     xlab = "Sepal Length", ylab = "Density", 
     main = "Density plot of multiple groups"); 

d <- lapply(split(iris$Sepal.Length, iris$Species), density)
Map(function(dens, col) polygon(dens, col = col), 
    dens = d, col = c('pink', 'lightgreen', 'lightblue')); 

legend("topright", levels(iris$Species), fill = c('pink', 'lightgreen', 'lightblue'))