在ggplot2中调整堆叠geom_bar的y轴原点

时间:2015-01-20 00:11:00

标签: r ggplot2

我想用ggplot2绘制堆积条形图,并且很难获得颜色映射和堆栈顺序。以下示例是从this SO answer开发的,以实现非零y轴原点,但正如您所看到的,它会产生其他问题。颜色未正确映射,绘图顺序错误。感谢有关处理此问题的最佳方法的任何指针。所需的输出应根据rating的因子级别缩放颜色,颜色按指定的顺序排列。

require(ggplot2)
d = data.frame(grp = rep(c('A','B'), each = 4), 
               rating = rep(c('bad','poor','ok','good'), 2),
               value = c(15,45,35,5,5,15,55,30), stringsAsFactors = F)

if(require(reshape2)) reshape2::dcast(d, grp ~ rating) # show structure

d$rating = ordered(d$rating, levels=c('bad','poor','ok','good'))
d$grp = ordered(d$grp, levels=c('B','A'))

# split datsets so we can plot 'negative' bars
d1 = subset(d, rating %in% c('ok','good'))
d2 = subset(d, rating %in% c('poor','bad'))

ggplot() + 
  geom_bar(data = d1, aes(x=grp, y=value, fill=rating), stat='identity', position='stack') + 
  geom_bar(data = d2, aes(x=grp, y=-value, fill=rating), stat='identity', position='stack') + 
  scale_fill_manual(values=c('red','pink','lightgreen','green')) +
  geom_line(data=d1, aes(x=c(.5,2.5), y=c(0,0)), size=2, linetype='dashed') +
  coord_flip()

enter image description here

1 个答案:

答案 0 :(得分:1)

也许有点重新排序和使用limits()会有所帮助:

d2 <- d2[order(d2$rating, decreasing =T),]

ggplot() + 
     geom_bar(data = d1, aes(x=grp, y=value, fill=rating), stat='identity',
               position='stack') + 
     geom_bar(data = d2, aes(x=grp, y=-value, fill=rating), stat='identity', 
               position='stack') + 
     scale_fill_manual(values=c('red','pink','lightgreen','green'),
                       limits=c("bad","poor","ok","good"))+
     geom_line(data=d1, aes(x=c(.5,2.5), y=c(0,0)), size=2, linetype='dashed') +
     coord_flip()

enter image description here

对于任何想要学习ggplot2的人,我强烈建议你选择Winston Chang的R Graphics Cookbook