奇怪的ggplot堆积条形输出

时间:2016-04-23 11:26:20

标签: r ggplot2 dplyr tidyr

我有几十个情节要复杂得多,但由于某些原因,我的大脑并没有把这个用掉......

给出数据框和代码......

# libraries
 require(ggplot2)
 require(dplyr)
 require(tidyr)

# create data
 data <- data.frame("When"=c("(2008 - 2009)","(2010 - 2011)","(2012 - 2013)","(2014-2015)","Cannot Remember"),
                    "Friend"=c(2,7,15,3,0),
                    "News Website"=c(2,10,8,3,1),
                    "Printed Newspaper"=c(0,1,3,0,0),
                    "Academic Paper"=c(0,0,2,0,0),
                    "Online Forum"=c(6,16,25,6,1),
                    "Cannot Remember"=c(1,3,7,2,1)
                    )

# reshape to long format
 data <- gather(data,var,val,2:7) 

# plot stacked bar
 ggplot(data[which(data$val>0),],aes(x=When, Y=val)) +
       geom_bar( aes(fill=var)) 

我得到了一个堆叠的酒吧甚至尝试按照this post重塑但是酒吧(和子酒吧)肯定不是表中的值,在6点高出我不能为我的生活看到为什么。到目前为止,2个小时的摆弄,我无法做到这一点。

Not the plot I was expecting

请有人能保存我的大脑吗?

1 个答案:

答案 0 :(得分:2)

您好Y的大写字母为aes,您必须设置stat = "identity",请尝试:

ggplot(data[which(data$val>0),],aes(x=When, y=val)) +
  geom_bar( aes(fill=var), stat = "identity")