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

Adjusting y axis origin for stacked geom_bar in ggplot2

我想用 ggplot2 绘制堆叠条形图,但很难正确设置颜色映射和堆叠顺序。下面的示例是从 this SO answer 开发的,以实现 non-zero y-axis 来源,但如您所见,它产生了其他问题。颜色映射不正确,绘图顺序错误。感谢您提供有关处理此问题的最佳方法的任何指示。所需的输出应根据 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()

也许重新排序和使用 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()

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