首页 文章

在ggplot2中使用stat =“bin”标记堆积条形图

提问于
浏览
0

看起来ggplot2应该能够使用geom_text标记堆积条形图,并在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 <- 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")

我想包括结果图,但我的声誉级别不允许 . 我想要的是在每个相应的条上打印和居中 .

1 回答

  • 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")
    

相关问题