我发现当coord_flip()使用ggplot2 添加到某些图时,图例中值的顺序不再与图中值的顺序对齐.
例如:
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'))
Run Code Online (Sandbox Code Playgroud)

我希望在不改变图中'q'和'r'的顺序的情况下反转图例中的'q'和'r'.
scale.x.reverse() 看起来很有希望,但似乎并没有在因素范围内起作用(就像这个条形图的情况一样).
jor*_*ran 31
您正在寻找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))
Run Code Online (Sandbox Code Playgroud)
我在聊天提醒布赖恩,有是为任意排序做到这一点,通过设定一个更普遍的方式breaks的说法:
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"))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6796 次 |
| 最近记录: |