具有组的躲避条形图的自定义条宽度

时间:2014-11-26 22:47:16

标签: r ggplot2

具有可变宽度的绘图条是一个常见的请求,我在SO处找到了许多解决方案,但它们似乎只有在情节由单个条形图组成时才有效,而我将它们分组:

set.seed(1)
dat <- data.frame(group=c('foo', 'foo', 'foo', 'bar', 'xyz', 'xyz'), 
                  indiv=c('foA', 'foB', 'foC', 'baD', 'xyE', 'xyF'),
                  val=sample(30:90, 6),
                  wid=sample(2:8, 6)
                  )

ggplot(dat, aes(x=group, y=val)) + 
  geom_bar(aes(fill=indiv), stat="identity", position="dodge") +
  theme_bw() # btw this also doesn't work as expected but that's another question

这是我得到的: what I get

我需要的是这样的事情: desired result

(此图片是我在下面的答案中显示的解决方法的结果)

1 个答案:

答案 0 :(得分:1)

我会在这里提出我的解决方案,但我觉得它很难看,如果有人能提出更好的解决方案,我会很高兴。

# convert to data.table -
# just because I'm more familiar with it, otherwise just use `plyr`
dat <- data.table(dat)

# assign number to each group:
dat[, grp:=.GRP, by=group]

gap <- 2 # gap width

# coordinate of each bar:
dat$pos <- dat$grp*gap + 0.5 * (cumsum(dat$wid) + cumsum(c(0, dat$wid[-length(dat$wid)])))

#coordinate of each group's label:
grppos <- dat[, (min(pos-wid/2)+max(pos+wid/2))/2, by=group]

# draw plot
ggplot(dat, aes(x=pos, y=val)) + 
  geom_bar(aes(width=wid), stat="identity", col='black') +
  scale_x_continuous(labels=grppos$group, breaks=grppos$V1)