gpt4 book ai didi

r - ggplot2:添加描述散点图两个维度的条件密度曲线

转载 作者:行者123 更新时间:2023-12-04 06:17:19 24 4
gpt4 key购买 nike

我有来自两个类别的二维数据的散点图。我想为每个维度添加密度线——不在绘图之外(参见 Scatterplot with marginal histograms in ggplot2),而是在绘图表面上。我可以为 x 轴维度得到这个,如下所示:

set.seed(123)
dim1 <- c(rnorm(100, mean=1), rnorm(100, mean=4))
dim2 <- rnorm(200, mean=1)
cat <- factor(c(rep("a", 100), rep("b", 100)))
mydf <- data.frame(cbind(dim2, dim1, cat))
ggplot(data=mydf, aes(x=dim1, y=dim2, colour=as.factor(cat))) +
geom_point() +
stat_density(aes(x=dim1, y=(-2+(..scaled..))),
position="identity", geom="line")

它看起来像这样:

enter image description here

但我想要一对类似的垂直运行的密度曲线,显示 y 维度中点的分布。我试过
stat_density(aes(y=dim2, x=0+(..scaled..))), position="identity", geom="line)

但收到错误“stat_密度需要以下缺失的美学:x”。

有任何想法吗?谢谢

最佳答案

您可以获得dim2 变量的密度。然后,翻转轴并将它们存储在新的 data.frame 中。之后,它只是将它们绘制在另一个图形的顶部。

p <- ggplot(data=mydf, aes(x=dim1, y=dim2, colour=as.factor(cat))) + 
geom_point() +
stat_density(aes(x=dim1, y=(-2+(..scaled..))),
position="identity", geom="line")

stuff <- ggplot_build(p)
xrange <- stuff[[2]]$ranges[[1]]$x.range # extract the x range, to make the new densities align with y-axis

## Get densities of dim2
ds <- do.call(rbind, lapply(unique(mydf$cat), function(lev) {
dens <- with(mydf, density(dim2[cat==lev]))
data.frame(x=dens$y+xrange[1], y=dens$x, cat=lev)
}))

p + geom_path(data=ds, aes(x=x, y=y, color=factor(cat)))

enter image description here

关于r - ggplot2:添加描述散点图两个维度的条件密度曲线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31168944/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com