R 使用stat=";标记堆叠条形图;“银行标识代码”;在ggplot2中

R 使用stat=";标记堆叠条形图;“银行标识代码”;在ggplot2中,r,ggplot2,labels,R,Ggplot2,Labels,ggplot2似乎应该能够使用geom_文本标记堆叠条形图,并在geom_bar中的数据帧子集上执行计数统计,而不必专门为标签重新创建新的数据帧。这可能吗 这就是我的数据框的外观: > head(df.m2) Community Categories Indicators Code Scores Condition 1 Zaragoza Landscape Landscape \n Composition f01.1

ggplot2似乎应该能够使用geom_文本标记堆叠条形图,并在geom_bar中的数据帧子集上执行计数统计,而不必专门为标签重新创建新的数据帧。这可能吗

这就是我的数据框的外观:

> 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我将使用
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") 
require(data.table)

dt.m2请,我相信你会找到几个很好的例子,你可以根据自己的数据进行调整。@Henrik是的,我今天在发布之前搜索并阅读了大约3个小时。我读过的书中没有一本专门针对我的问题。据我所知,解决方案非常复杂,使用plyr和其他此类软件包来处理数据,而不是简单地使用ggplot的统计功能。如果您正在考虑某个特定的帖子,欢迎您与我分享。感谢您的建议,我将不得不询问ggplot2人员关于在未来版本的标签中包含stat=“bin”。我还没有想出如何让你的解决方案起作用;错误比比皆是,产生的计数不适合我想要做的标记。但是,与我提出的问题相比,这更像是我的情节中的一个具体问题,所以我觉得没有必要跟进。谢谢你的帮助。
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")