R中具有gg图的堆积密度图

时间:2018-07-26 14:35:53

标签: r ggplot2 stacked

我无法正确绘制堆积密度图

这是我的data结构

Classes ‘tbl_df’, ‘tbl’ and 'data.frame':   8517 obs. of  3 variables:
 $ time  : num  -500 -499 -498 -497 -496 -495 -494 -493 -492 -491 ...
 $ series: Factor w/ 17 levels "V1","V2","V3",..: 1 1 1 1 1 1 1 1 1 1 ...
 $ value : num  0.0788 0.0625 0.0455 0.0323 0.0426 ...

这是我的代码

ggplot(data=data,aes(x=time, group=data$series, fill=data$series)) + 
    geom_density(adjust=1.5, position="fill")

但是它画了我的水平线

enter image description here

相反,我希望它可以绘制类似的内容

enter image description here

如果有人有任何想法?我将不胜感激。谢谢

这是我的数据结构

dput(head(data))
    structure(list(time = c(-500, -499, -498, -497, -496, -495), 
        series = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = c("V1", 
        "V2", "V3", "V4", "V5", "V6", "V7", "V8", "V9", "V10", "V11", 
        "V12", "V13", "V14", "V15", "V16", "V17"), class = "factor"), 
        value = c(0.0787576635451054, 0.0625, 0.0455255463892602, 
        0.0322986577181208, 0.0426306596802365, 0.0369765758489718
        )), row.names = c(NA, -6L), class = c("tbl_df", "tbl", "data.frame"
    ))

2 个答案:

答案 0 :(得分:0)

这对您有用吗?

ggplot(data, aes(x=time, fill = series)) + 
  geom_density(adjust=1.5, position="fill")

我不好,最初我有一个错误的主意,你快到了。

只需删除data$

答案 1 :(得分:0)

为了便于多方面说明,我对其进行了一点改动。

df <- structure(list(time = c(-500, -499, -498, -497, -496, -495), 
           series = structure(c(1L, 1L, 2L, 2L, 3L, 3L), .Label = c("V1", 
                                                                    "V2", "V3", "V4", "V5", "V6", "V7", "V8", "V9", "V10", "V11", 
                                                                    "V12", "V13", "V14", "V15", "V16", "V17"), class = "factor"), 
           value = c(0.0787576635451054, 0.0625, 0.0455255463892602, 
                     0.0322986577181208, 0.0426306596802365, 0.0369765758489718
           )), row.names = c(NA, -6L), class = c("tbl_df", "tbl", "data.frame"
           ))


ggplot(df, aes(x = time)) +
  geom_density(stat = "density", aes(fill = series), position = "stack") # or fill if you want proportions  

Stack Fill