Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
470 views
in Technique[技术] by (71.8m points)

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

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()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...