带有ggplot2的堆积条形图标签

时间:2011-11-23 14:13:17

标签: r ggplot2

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

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. 如果确实没有显示百分比(虽然我不完全确定这一点)
  3. 非常感谢任何帮助。谢谢!

1 个答案:

答案 0 :(得分:3)

文本的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
  )