Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

r - Flip ordering of legend without altering ordering in plot

I have found that when adding coord_flip() to certain plots using ggplot2 that the order of values in the legend no longer lines up with the order of values in the plot.

For example:

dTbl = data.frame(x=c(1,2,3,4,5,6,7,8),
                  y=c('a','a','b','b','a','a','b','b'),
                  z=c('q','q','q','q','r','r','r','r'))

print(ggplot(dTbl, aes(x=factor(y),y=x, fill=z)) +
      geom_bar(position=position_dodge(), stat='identity') +
      coord_flip() +
      theme(legend.position='top', legend.direction='vertical'))

enter image description here

I would like the 'q' and 'r' in the legend to be reversed without changing the order of 'q' and 'r' in the plot.

scale.x.reverse() looked promising, but it doesn't seem to work within factors (as is the case for this bar plot).

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You're looking for guides:

ggplot(dTbl, aes(x=factor(y),y=x, fill=z)) +
      geom_bar(position=position_dodge(), stat='identity') +
      coord_flip() +
      theme(legend.position='top', legend.direction='vertical') + 
      guides(fill = guide_legend(reverse = TRUE))

I was reminded in chat by Brian that there is a more general way to do this for arbitrary orderings, by setting the breaks argument:

ggplot(dTbl, aes(x=factor(y),y=x, fill=z)) +
      geom_bar(position=position_dodge(), stat='identity') +
      coord_flip() +
      theme(legend.position='top', legend.direction='vertical') + 
      scale_fill_discrete(breaks = c("r","q"))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...