在不改变绘图顺序的情况下翻转图例排序 [英] Flip ordering of legend without altering ordering in plot

查看:242
本文介绍了在不改变绘图顺序的情况下翻转图例排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现当使用ggplot2将 coord_flip()添加到某些图时,图例中值的顺序不再与图中值的顺序对齐。

例如:

pre $ 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()+
主题(legend.position ='top',legend.direction ='vertical'))



我希望图例中的'q'和'r'颠倒,而不会改变图中'q'和'r'的顺序。



比例。 x.reverse()看起来很有前途,但它似乎在因素内不起作用(就像这个柱状图那样)。

>解决方案

您正在寻找指南

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

Brian在聊天室提醒我, 是一种更通用的方式,通过设置 breaks 参数:

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


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'))

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).

解决方案

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"))

这篇关于在不改变绘图顺序的情况下翻转图例排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆