Out of order text labels on stack bar plot (ggplot)

笑着哭i 提交于 2019-12-17 21:28:45

问题


I'm trying to make a stacked bar chart with text labels, this some example data / code:

library(reshape2)

ConstitutiveHet <- c(7,13)
Enhancer <- c(12,6)
FacultativeHet <- c(25,39)
LowConfidence <- c(3,4)
Promoter <- c(5,4)
Quiescent <- c(69,59)
RegPermissive <- c(23,18)
Transcribed <- c(12,11)
Bivalent <- c(6,22)
group <- c("all","GWS")

meanComb <- data.frame(ConstitutiveHet,Enhancer,LowConfidence,Promoter,Quiescent,RegPermissive,Transcribed,Bivalent,group)
meanCombM <- melt(meanComb,id.vars = "group")

ggplot(meanCombM,aes(group,value,label=value)) +
     geom_col(aes(fill=variable))+
     geom_text(position = "stack")+
     coord_flip()

The text labels appear out of order, they seem to be the mirror image of their intended order. (you get the same problem with or without the coord_flip())

A poster had a similar problem here: ggplot2: add ordered category labels to stacked bar chart

An answer to their post propsed reversing the order of the values in the groups, which I tried (see below), the resulting order on the plot is not one i've been able to figure out. Also this approach seems hacky, is there a bug here or am I missing something?

x <- c(rev(meanCombM[meanCombM$group=="GWS",]$value),rev(meanCombM[meanCombM$group=="all",]$value))

ggplot(meanCombM,aes(group,value,label=x)) +
geom_col(aes(fill=variable))+
geom_text(position = "stack")+
coord_flip()

回答1:


ggplot(meanCombM,aes(group,value,label=value)) +
     geom_col(aes(fill=variable))+
     geom_text(aes(group=variable),position = position_stack(vjust = 0.5))+
     coord_flip()

Hadley answered a question similar to my own in this issue in ggplot2's git repository: https://github.com/tidyverse/ggplot2/issues/1972

Apparently the default grouping behaviour (see: http://ggplot2.tidyverse.org/reference/aes_group_order.html) does not partition the data correctly here without specifying a group aesthetic, which should map to the same value as fill in geom_col in this example.



来源:https://stackoverflow.com/questions/47699146/out-of-order-text-labels-on-stack-bar-plot-ggplot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!