ggplot2无法识别熔融数据中的值

时间:2016-05-06 22:47:28

标签: r plot ggplot2 reshape2

我试图按照这里的例子制作一个简单的堆积密度图:Create a stacked density graph in ggplot2

我使用的是融化数据,但当我尝试使用"值"在y轴上,我收到一个错误。

这是我的原始数据:

> str(bug)
'data.frame':   39 obs. of  10 variables:
 $ year           : int  2006 2006 2006 2006 2006 2006 2006 2006 2006 2006 ...
 $ SampleDate     : Factor w/ 39 levels "01-Aug-07","02-Jun-06",..: 21 32 2 11 19 28 37 8 17 24 ...
 $ Oligochaeta    : int  905 604 371 991 213 144 1 14 5 5 ...
 $ Copepoda       : int  586 352 12 602 45 24 3 1 1 8 ...
 etc. 

这就是我用熔体的方式:

> mbug <- melt(bug, id.vars=c("year", "SampleDate"))

我更正了日期格式:

> mbug$date1 <- as.Date(mbug$SampleDate, "%d-%b-%y")

这是熔化的数据:

> str(mbug)
'data.frame':   312 obs. of  5 variables:
 $ year      : int  2006 2006 2006 2006 2006 2006 2006 2006 2006 2006 ...
 $ SampleDate: Factor w/ 39 levels "01-Aug-07","02-Jun-06",..: 21 32 2 11 19 28 37 8 17 24 ...
 $ variable  : Factor w/ 8 levels "Oligochaeta",..: 1 1 1 1 1 1 1 1 1 1 ...
 $ value     : int  905 604 371 991 213 144 1 14 5 5 ...
 $ date1     : Date, format: "2006-05-18" "2006-05-26" "2006-06-02" "2006-06-09" ...

我使用了ggplot和熔化数据:

> ggplot(mbug, aes(x=date1, y=value)) +
+ geom_density(aes(fill=variable), position="stack")
+ facet_wrap(~ year, nrow=1) + theme(text = element_text(size = 22))

最后出现了这个错误:

Error in eval(expr, envir, enclos) : object 'y' not found

最终,我希望变量被称为&#34; taxon&#34;和值#34;丰度&#34;,但我总能在ggplot中做到这一点。现在,我的主要目标是能够策划y!

提前致谢。

1 个答案:

答案 0 :(得分:2)

看起来你想要的不是密度图,而是valuedate1的区域图。也许这样的事情,但很难确定无法处理您的数据样本:

ggplot(mbug, aes(x=date1, y=value, fill=variable)) +
    geom_area() +
    facet_wrap(~ year, nrow=1) + 
    theme(text = element_text(size = 22))

为了比较,这是一个假数据的例子:

set.seed(984)
dat = data.frame(time=rep(1980:2020,2), 
                 value=c(cumsum(rnorm(41,10,20)),cumsum(rnorm(41,10,20))),
                 group=rep(c("A","B"), each=41))

ggplot(dat, aes(time, value, fill=group)) + 
  geom_area() +
  theme_bw()

enter image description here

密度图是平滑的直方图,给出单个变量的分布。密度绘制在y轴上,并由ggplot在内部计算。例如,如果我想要分配车辆燃油经济性(即每个燃油经济性区间内的汽车比例),我可以这样做:

ggplot(mtcars, aes(mpg)) + geom_density()

但如果我执行以下操作,则会导致您遇到同样的错误:

ggplot(mtcars, aes(x=wt, y=mpg) + geom_density()

这是因为密度图中的“y”值是每个x值的x变量的密度(y轴上的高度)。