【问题标题】:Stacked Bar Graph Labels with ggplot2使用 ggplot2 堆叠条形图标签
【发布时间】:2012-01-04 19:54:35
【问题描述】:

我正在尝试绘制以下数据:

to_graph <- structure(list(Teacher = c("BS", "BS", "FA"
), Level = structure(c(2L, 1L, 1L), .Label = c("BE", "AE", "ME", 
"EE"), class = "factor"), Count = c(2L, 25L, 28L)), .Names = c("Teacher", 
"Level", "Count"), row.names = c(NA, 3L), class = "data.frame")

并希望在每条条的中间添加标签,这些标签是该条的百分比。基于this post,我想出了:

ggplot(data=to_graph, aes(x=Teacher, y=Count, fill=Level), ordered=TRUE) + 
    geom_bar(aes(fill = Level), position = 'fill') + 
    opts(axis.text.x=theme_text(angle=45)) + 
    scale_y_continuous("",formatter="percent") + 
    opts(title = "Score Distribution") + 
    scale_fill_manual(values = c("#FF0000", "#FFFF00","#00CC00", "#0000FF")) + 
    geom_text(aes(label = Count), size = 3, hjust = 0.5, vjust = 3, position = "stack")

但是

  1. 对图表没有任何影响
  2. 如果显示的话,可能不会显示百分比(尽管我不完全确定这一点)

非常感谢任何帮助。谢谢!

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    文本的 y 坐标是实际计数(2、25 或 28),而绘图面板中的 y 坐标范围是 0 到 1,因此文本是从顶部打印出来的。

    使用ddply(或tapply 或其他)计算计数的分数。

    graph_avgs <- ddply(
      to_graph, 
      .(Teacher), 
      summarise, 
      Count.Fraction = Count / sum(Count)
    )
    
    to_graph <- cbind(to_graph, graph_avgs$Count.Fraction)
    

    情节的简化版本。我还没有费心处理因子顺序,所以数字与条形匹配。

    ggplot(to_graph, aes(Teacher), ordered = TRUE) + 
      geom_bar(aes(y = Count, fill = Level), position = 'fill') + 
      scale_fill_manual(values = c("#FF0000", "#FFFF00","#00CC00", "#0000FF")) + 
      geom_text(
        aes(y = graph_avgs$Count.Fraction, label = graph_avgs$Count.Fraction),  
        size = 3
      )
    

    【讨论】:

    • 感谢您的回复。我目前的代码出现此错误: do.call("layer", list(mapping = mapping, data = data, stat = stat, : object 'Count' not found) 中的错误
    • 这是有道理的,但由于某种原因,当我进行合并时,它基本上对数据进行了外连接。我得到 structure(list(Teacher = c("BS", "BS", "BS", "BS", "FA"), Level = structure(c(2L, 2L, 1L, 1L, 1L), .Label = c("BE", "AE", "ME", "EE"), class= "因子"), Count = c(2L, 2L, 25L, 25L, 28L), Count.Fraction = c(0.0740740740740741, 0.925925925925926, 0.0740740740740741, 0.925925925925926, 1)), .Names = c("Teacher", "Level", "Count", "Count.Fraction"), row.names = c(NA, -5L), class= "data .frame")
    • 我尝试添加 by="Teacher" 但没有运气......有什么想法吗?谢谢!
    • 所以,我最终使用 cbind 而不是仅与 Count.Fraction 列合并。这会以正确的格式获取数据,以了解我如何措辞问题。然后我将标签更改为 Count.Percentage 列以获取百分比而不是计数,正如我的问题中所概述的那样。感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多