首页 > 解决方案 > 如何使用多边形函数获得密度图?我有多个组要绘制

问题描述

所以我在R中使用了基本数据,“iris”数据

到目前为止,我所做的是创建一个向量,该向量具有带有 Sepal.Length 的 x 值和具有密度函数输出的 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])
}

输出

这是输出它应该是什么样子

预期答案

太感谢了

标签: rplotpolygonkernel-densitydensity-plot

解决方案


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

library(ggplot2)

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

如果您想在基础绘图中执行此操作,通常最简单的方法是先设置空窗口,然后遍历组。由于您需要设置颜色和组,Map因此比lapply. 传奇需要额外的电话。

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'))


推荐阅读