【问题标题】:How to display value in a stacked bar chart by using geom_text?如何使用 geom_text 在堆积条形图中显示值?
【发布时间】:2012-11-27 01:36:26
【问题描述】:

我想在堆积栏中显示百分比数字。但是,其中一组的比例非常低。两个值相互重叠。我改为'职位='身份'。它仍然无法工作......有什么想法吗?

x4.can.m <- structure(list(canopy = structure(c(1L, 2L, 3L, 1L, 2L, 3L, 1L, 
2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L), .Label = c("0%", "1 to 84%", 
"85% +"), class = "factor"), YearQuarter = structure(c(1L, 1L, 
1L, 2L, 2L, 2L, 3L, 3L, 3L, 4L, 4L, 4L, 5L, 5L, 5L), .Label = c("2011-09-01", 
"2011-12-01", "2012-03-01", "2012-06-01", "2012-09-01"), class = "factor"), 
    value = c(0.51, 0.01, 0.48, 0.52, 0.01, 0.47, 0.53, 0.01, 
    0.47, 0.57, 0.01, 0.41, 0.61, 0.01, 0.38)), .Names = c("canopy", 
"YearQuarter", "value"), row.names = c(NA, -15L), class = "data.frame")


x4.can.bar <- ggplot(data=x4.can.m, aes(x=factor(YearQuarter), y=value,fill=canopy)) + geom_bar(stat="identity",position = "stack",ymax=100)

x4.can.bar+scale_y_continuous(formatter='percent')+
 labs(y="Percentage",x="Year Quarter") + 
 geom_text(aes(label =paste(round(value*100,0),"%",sep="")),size = 3, hjust = 0.5, vjust = 4,position ="identity")

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    您需要为标签的位置指定合理的值 - 如果您在 ggplot 调用之外执行此操作,这将比尝试在调用中执行此操作要容易得多。

    您可以通过取每个堆叠组件的中点来做到这一点。

    使用plyrddply 很简单,只需将每个YearQuarter 中的累加和减去当前值的一半

    library(plyr)
    x4.can.m <- ddply(x4.can.m, .(YearQuarter), mutate, csum = cumsum(value)-value/2)
    
    x4.can.bar <- ggplot(data=x4.can.m, aes(x=factor(YearQuarter), y=value,fill=canopy)) +  
     geom_bar(stat="identity",position = "stack",ymax=100)
    
    x4.can.bar + 
     scale_y_continuous(expand = c(0,0), labels = percent) +
     labs(y="Percentage",x="Year Quarter")+
     geom_text(aes(y = csum,label =paste(round(value*100,0),"%",sep="")),
               size = 3, hjust = 1, vjust = 0)
    

    请注意,我使用的是ggplot2_0.9.2.1,因此formatter 不再是scale_y_continuous 的有效参数,而是替换为label = percent。见this question及相关链接

    【讨论】:

    • @mnel,谢谢。升级到 ggplot2_0.9.2.1 的最简单方法是什么。我还在使用 R_2.15.1 .....
    • 在新的 R 会话中运行 install.packages('ggplot2')
    • R_2.15.0.2中melt()函数消失了吗?
    • 没有。 ggplot2 用于将reshape2 加载到搜索路径中,较新版本的import reshape2 因此函数可用于ggplot2。运行 library(reshape2) 以显式加载。
    【解决方案2】:

    一种解决方案是将堆栈栏更改为闪避一

    x4.can.bar <- ggplot(data=x4.can.m, aes(x=factor(YearQuarter), y=value,fill=canopy)) + 
                        geom_bar(stat="identity",position = "dodge",ymax=100) +
                 geom_text(aes(label =paste(round(value*100,0),"%",sep=""),ymax=0), 
                           position=position_dodge(width=0.9), vjust=-0.25)
    x4.can.bar
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-25
      • 1970-01-01
      • 2021-09-07
      • 2014-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多