中心标签堆积条(计数)ggplot2 [英] Center labels stacked bar (counts) ggplot2

查看:138
本文介绍了中心标签堆积条(计数)ggplot2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用这种方法将标签放置在一个堆积条形图上(尽管如果现在有更好的方法,我可以开放):

在ggplot2中的堆叠条形图上显示数据值



这是我的原始情节:

 数据<  -  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)



如何在每个填充部分中标注标签?

解决方案

无关的 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,。(g ear),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)


I'm attempting to place labels on a stacked bar plot using this approach (though if there's now a better approach I'm open to what ever):

Showing data values on stacked bar chart in ggplot2

Here's my original plot:

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)

Here's my attempt to center labels in each fill section:

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)

How can I center the labels in each fill section?

解决方案

There's some extraneous ddply action going on with this one as I knew the solution I wanted but was having trouble keeping the frequencies aligned with the positions, but I think the algorithm for finding the group midpoints is worth posting:

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)

这篇关于中心标签堆积条(计数)ggplot2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆