r - 如何使用多边形函数获得密度图?我有多个组要绘制
问题描述
所以我在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])
}
这是输出它应该是什么样子
太感谢了
解决方案
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'))
推荐阅读
- javascript - Javascript - 我如何让点击动作只应用于上层元素
- javascript - [已解决]ApexCharts.js:如何为折线图中的轴标签设置固定值
- reactjs - React setState hook异步更新问题
- javascript - 闭包如何在 addEventListener 中工作?
- c - 计算点相交的沿纬度长向量的距离
- sharepoint - 使用 jsom 在 Sharepoint 中获取术语及其子术语
- google-colaboratory - 如何从其他公共驱动器直接将谷歌驱动器文件夹下载到colab而不下载到PC?
- javascript - Reactjs没有显示从状态生成的动态数据
- ios - Info.plist 文件未更新位置
- ruby-on-rails - Rails 6 Active Job“retry_stopped.active_job”订阅未触发