【问题标题】:Center labels stacked bar (counts) ggplot2中心标签堆叠条(计数)ggplot2
【发布时间】:2013-09-25 01:12:44
【问题描述】:

我正在尝试使用这种方法在堆积条形图上放置标签(尽管如果现在有更好的方法我愿意接受):

Showing data values on stacked bar chart in ggplot2

这是我原来的情节:

dat <- data.frame(with(mtcars, table(cyl, gear)))

ggplot(dat, aes(x = gear, fill = cyl)) +
    geom_bar(aes(weight=Freq), position="stack") +
    geom_text(position = "stack", aes(x = gear, y = Freq, 
        ymax = 15, label = cyl), size=4)

这是我在每个填充部分中将标签居中的尝试:

dat2 <- ddply(dat, .(cyl), transform, pos = cumsum(Freq) - 0.5*Freq)

library(plyr)
ggplot(dat2, aes(x = gear, fill = cyl)) +
    geom_bar(aes(weight=Freq), position="stack") +
    geom_text(position = "stack", aes(x = gear, y = pos, 
        ymax = 15, label = cyl), size=4)

如何将每个填充部分的标签居中?

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    有一些无关的ddply 操作正在进行,因为我知道我想要的解决方案,但是在保持频率与位置对齐时遇到了麻烦,但我认为找到组中点的算法值得发布:

    group_midpoints = function(g) {
      cumsums = c(0, cumsum(g$Freq))
      diffs = diff(cumsums)
      pos = head(cumsums, -1) + (0.5 * diffs)
      return(data.frame(cyl=g$cyl, pos=pos, Freq=g$Freq))
    }
    
    dat3 = ddply(dat, .(gear), group_midpoints)
    
    ggplot(dat3, aes(x = gear, fill = cyl)) +
      geom_bar(aes(weight=Freq), position="stack") +
      geom_text(position = "identity", aes(x = gear, y = pos, ymax = 15, label = cyl), size=4)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-04
      • 2020-09-07
      • 1970-01-01
      • 2014-08-30
      • 1970-01-01
      • 2021-01-17
      • 2018-02-27
      相关资源
      最近更新 更多