首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在r中添加了坡度线的多密度图

在r中添加了坡度线的多密度图
EN

Stack Overflow用户
提问于 2021-08-10 15:23:44
回答 1查看 65关注 0票数 0

我想创建具有多个组的密度图,并为平均值添加坡度线。该图如下所示:

代码语言:javascript
运行
复制
library(tidyverse)
library(ggridges)
data1 <- data.frame(x1 = c(rep(1,50), rep(2,50), rep(3,50), rep(4,50), rep(5,50)),
                    y1 = c(rnorm(50,10,1), rnorm(50,15,2), rnorm(50,20,3), rnorm(50,25,3), rnorm(50,30,4)))
data1$x1 <- as.factor(data1$x1)
ggplot(data1, aes(x = y1, y = x1, fill = 0.5 - abs(0.5 - stat(ecdf)))) +
  stat_density_ridges(geom = "density_ridges_gradient", calc_ecdf = TRUE) +
  scale_fill_viridis_c(name = "Tail probability", direction = -1)

EN

Stack Overflow用户

回答已采纳

发布于 2021-08-10 21:28:43

有两种方法可以构建红线。您可以(1)通过表示组平均值的点使用geom_line,或者(2)通过数据拟合回归。

(1)将被截断以适合数据,(2)可以扩展到数据之外,但只有在x和y之间存在整体线性关系时才会看起来正确。

(1)的代码

代码语言:javascript
运行
复制
means <- aggregate(y1 ~ x1, data=data1, FUN=mean)

ggplot(data1, aes(x = y1, y = x1, fill = 0.5 - abs(0.5 - stat(ecdf)))) +
  stat_density_ridges(geom = "density_ridges_gradient", calc_ecdf = TRUE) +
  scale_fill_viridis_c(name = "Tail probability", direction = -1) +
  geom_line(aes(x=y1, y=as.numeric(x1), fill=1), data=means, colour="red")
  // NB: need to override the fill aesthetic or you get an error

代码(2)

代码语言:javascript
运行
复制
regressionLine <- coef(lm(as.numeric(x1) ~ y1 , data=data1))
ggplot(data1, aes(x = y1, y = x1, fill = 0.5 - abs(0.5 - stat(ecdf)))) +
  stat_density_ridges(geom = "density_ridges_gradient", calc_ecdf = TRUE) +
  scale_fill_viridis_c(name = "Tail probability", direction = -1) +
  geom_abline(intercept=regressionLine[1], slope=regressionLine[2], colour="red")
票数 2
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68729530

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档