2013-10-28 89 views
0

似乎ggplot2应该能够使用geom_text标记堆叠条形图,并在geom_bar中对数据框的子集执行统计统计,而无需重新创建新的数据帧专门用于标签。这可能吗?在ggplot2中为stat =“bin”标记堆积条形图

这是我的数据帧是什么样子:

> head(df.m2) 
Community  Categories    Indicators Code Scores Condition 
1 Zaragoza   Landscape Landscape \n Composition f01.1  0 Marginal 
2 Zaragoza   Landscape    Windbreaks f01.1  6 Acceptable 
3 Zaragoza   Landscape  Field \n Location f01.1  6 Acceptable 
4 Zaragoza   Landscape  Soil \n Conservation f01.1  12 Optimal 
5 Zaragoza Farmer Management   Crop \n Rotation f01.1  12 Optimal 
6 Zaragoza Farmer Management  Crop \n Varieties f01.1  6 Acceptable 

这里是我使用创建我的阴谋(注意用来总结分类变量的STAT =“BIN”)的代码:

p <- ggplot(df.m2, aes(Indicators, fill=Condition)) 
p + coord_cartesian(ylim=c(-.3,12.3)) + 
geom_bar(stat="bin", colour="gray", alpha=.7) + 
scale_fill_manual(values = c("green","yellow","red")) + 
theme(axis.text.x = element_text(angle = 90,vjust= .5,hjust=1)) + 
labs(x = "Farmers' Indicators", y = "Number of Rankings by Farmers") + 
facet_grid(Community ~ Categories, scales = "free_x") 

我想包括最终的情节,但我的声望水平不允许它。我想要的是在每个相应的栏上打印和居中计数。

+0

请[在SO搜索](http://stackoverflow.com/search?q= [ggplot] + label + stacked + bar),我相信你会找到几个很好的例子,你可以适应你的自己的数据。 – Henrik

+0

@Henrik是的,我在发布之前,今天搜索了大约3个小时。我没有读到具体解决我的问题。从我所知道的情况来看,解决方案非常复杂,并且使用plyr和其他类似的包来操纵数据,而不是简单地使用ggplot的统计功能。如果您正在考虑某个帖子,欢迎与我分享。 – proge

回答

0

我会使用这个data.table包。它仍然不起作用,只有ggplot的能力。通常最好先做数据调整,然后使用ggplot

require(data.table) 
dt.m2 <- data.table(df.m2) 
dt.m2[, count:=.N, by=list(Indicators, Categories)] # create the count index 
# almost the same as before 
p <- ggplot(dt.m2, aes(Indicators, fill=Condition)) 
p + coord_cartesian(ylim=c(-.3,12.3)) + 
    geom_bar(stat="bin", colour="gray", alpha=.7) + 
    geom_text(aes(y=count+1, label=paste0("n=", count))) + # add text above bar 
    # you may have to change the y position for this to look good 
    scale_fill_manual(values = c("green","yellow","red")) + 
    theme(axis.text.x = element_text(angle = 90,vjust= .5,hjust=1)) + 
    labs(x = "Farmers' Indicators", y = "Number of Rankings by Farmers") + 
    facet_grid(Community ~ Categories, scales = "free_x") 
+0

感谢您的建议,我将不得不问ggplot2有关在未来版本中添加stat =“bin”的标签。我还没有弄清楚如何让你的解决方案工作。错误比比皆是,产生的计数不适合我想要做的标记。但是,这更像是我的情节中的一个特定问题,而不是与我所问的问题通常有关,所以不要紧随其后。谢谢您的帮助。 – proge