r - ggplot2 中的 cdplot() 模拟

标签 r ggplot2 distribution

我正在寻找像 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/

相关文章:

r - 如何在ggplot2中绘制png图像?

iphone - iOS App 的系统设置是否可以通过 Enterprise Distribution 配置?

macos - 我们可以临时分发 MAC 应用程序吗?

r - 导入 .xlsx 文件后,从矩阵列表构建适当的数据框

r - ggplot 颜色以具有预定义调色板的其他列为条件

r - 在旋转坐标上查找轴线

push-notification - 为临时分发环境启用 Apple 推送通知

r - 如何在 R 中的 ggplot2 中的瓷砖上放置标签?

r - 处理 r 中时间序列中的缺失值

R:计算滚动中位数和滚动平均值时出错