使用geom_bar根据R

时间:2017-06-29 04:15:26

标签: r ggplot2

我是R的新手,我正在尝试使用ggplot一起创建每个id的条形图子集。每个条形必须表示d列中每月的值(c列)的总和。 d也有NA值和数值。

我的数据框df是这样的,但它实际上有大约10000行:

#Example of my data
a=c(1,1,1,1,1,1,1,1,3)
b=c("2007-12-03", "2007-12-10", "2007-12-17", "2007-12-24", "2008-01-07", "2008-01-14", "2008-01-21", "2008-01-28","2008-02-04")
c=c(format(b,"%m-%Y")[1:9])
d=c(NA,NA,NA,NA,NA,4.80, 0.00, 5.04, 3.84)
df=data.frame(a,b,c,d)
df

  a          b       c    d
1 1 2007-12-03 12-2007   NA
2 1 2007-12-10 12-2007   NA
3 1 2007-12-17 12-2007   NA
4 1 2007-12-24 12-2007   NA
5 1 2008-01-07 01-2008   NA
6 1 2008-01-14 01-2008 4.80
7 1 2008-01-21 01-2008 0.00
8 1 2008-01-28 01-2008 5.04
9 3 2008-02-04 02-2008 3.84

我试图用这个来做我的图:

mplot<-ggplot(df,aes(y=d,x=c))+
       geom_bar()+
       theme(axis.text.x = element_text(angle=90, vjust=0.5))+
       facet_wrap(~ a)

我在geom_bar()的帮助下阅读:

  

“geom_bar默认使用stat_count:它计算每个x位置的个案数”

所以,我认为这样就可以解决这个错误:

Error: stat_count() must not be used with a y aesthetic.

对于我提供的样本,我想要id为1的图表,显示NA为空的月份和01-2008为9.84的月份。然后对于第二个id,我想再次使用NA为空,02-2008为3.84。

我还试图通过使用聚合和总和来绘制每月的数据,然后在geom_bar的stat参数中使用identity,但是,我在几个月内得到NA而且我不知道原因。

我真的非常感谢你的帮助。

3 个答案:

答案 0 :(得分:0)

你想要这样的东西:

mplot = ggplot(df, aes(x = b, y = d))+
  geom_bar(stat = "identity", position = "dodge")+
  facet_wrap(~ a)

mplot

enter image description here

我现在正在使用x = b而不是x = c

答案 1 :(得分:0)

你应该使用geom_col而不是geom_bar。请参阅帮助文本:

  

有两种类型的条形图:geom_bar使条形图的高度与每组中的个案数量成比例(或者如果提供了重量合计,则为权重的总和)。如果您希望条形的高度表示数据中的值,请改用geom_col。 geom_bar默认使用stat_count:它计算每个x位置的个案数。 geom_col使用stat_identity:它按原样保留数据。

所以你的最后一行代码应该是:

ggplot(df, aes(y=d, x=c)) + geom_col() + theme(axis.text.x = element_text(angle=90, vjust=0.5))+facet_wrap(~ a)

答案 2 :(得分:0)

不需要按照@Jan的建议使用geom_col。只需使用weight美学:

ggplot(iris, aes(Species, weight=Sepal.Width)) + geom_bar() + ggtitle("summed sepal width")
相关问题