gpt4 book ai didi

r - ggplot2 中的 cdplot() 模拟

转载 作者:行者123 更新时间:2023-12-01 23:16:28 25 4
gpt4 key购买 nike

我正在寻找像 R 内置的条件密度图 cdplot函数,但使用ggplot2 .

这是 Vanilla cdplot示例:

with(iris, cdplot(Sepal.Length, Species))

cdplot example

the ggplot2 book (第 188 页),它说以下调用应该是等效的:

cdplot(x, y)
qplot(x, fill=y, geom="density", position="fill")

但是,该行为似乎在 ggplot2 的某些更新中出现问题。 (它还发出警告说 `position` is deprecated ):

with(iris, qplot(Sepal.Length, fill=Species, geom="density", position="fill"))

ggplot example

我找到了a blog entry of someone trying to do the same thing ,但显然现在也被破坏了(同样的警告,`position` is deprecated):

cdens <- cdplot(iris$Sepal.Length, iris$Species, plot = F)
x <- seq(min(iris$Sepal.Length), max(iris$Sepal.Length), length.out = 100)
y <- c(cdens[[1]](x), cdens[[2]](x), rep(1, length(x)))
type <- ordered(rep(levels(iris$Species), each = length(x)),
levels=rev(levels(iris$Species)))
x <- rep(x, 3)
qplot(x, y, geom="area", fill = type, position="identity",
xlab="Sepal.Length", ylab="Species") + theme_bw()

enter image description here

有什么方法可以实现这一点?这些示例中出现了什么问题?

(我想要 ggplot 解决方案,因为它具有更好的轴标签和图例,特别是当自变量是日期时。)

更新:在下面的评论中,@bouncyball 建议使用 ggplot(iris, aes(x = Sepal.Length, fill = Species))+ geom_density(position = 'fill') ,但这是在做一些不同的事情:

with(data, cdplot(time, cat))
abline(v=as.POSIXct(c('2017-04-01', '2017-03-01')), col='red')

enter image description here

ggplot(data, aes(x=time, fill=cat)) + geom_density(position = 'fill')

enter image description here

cdplot结果是我想要的,我不确定ggplot是什么例子就是做。 cdplot结果与因子比率相匹配,例如 2017 年 3 月:

> with(subset(data, time>'2017-03-01' & time <'2017-04-01'), table(cat))
cat
<1s <3s <5s <10s <20s <1m <2m <5m <1h <24h >1d
175484 31837 19078 16146 15013 20200 1142 1207 944 17 0

最佳答案

使用计算变量count绘制堆积密度图,并根据cdplot重新排序物种水平。

library(ggplot2)
ggplot(iris, aes(Sepal.Length, ..count.., fill = forcats::fct_relevel(Species,
levels = c("virginica", "versicolor", "setosa")))) +
geom_density(position = "fill") +
labs(fill = "Species")

enter image description here

关于r - ggplot2 中的 cdplot() 模拟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46714058/

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