在ggplot2的facet_wrap中按y轴对x轴分面独立重排序
分面内按数值降序重排序坐标轴
你的示例代码
set.seed(1) x <- replicate(n = 5, 'left') y <- replicate(n = 5, 'right') dir <- c(x,y) quantity <- sample(seq(1,100), 10) names <- rep(letters[1:5],2) tb <- tibble(dir,quantity,names) %>% group_by(dir) %>% arrange(desc(quantity)) tb %>% ggplot(aes(x = fct_inorder(names), quantity)) + geom_bar(stat = 'identity', color = 'black') + coord_flip() + facet_wrap(~dir, scales = "free")
当前图表效果

需求
左右两个分面的x轴(经coord_flip()后对应视觉上的y轴)都按quantity的降序重排序。
解决办法
之所以没实现分面内各自排序,是因为fct_inorder()是按整个数据框的行顺序设置因子水平,不是每个分组内部的顺序。可以用以下两种方法解决:
方法1:分组内用fct_reorder()直接排序
在分组里用fct_reorder(),通过-quantity指定按降序排列:
library(tidyverse) set.seed(1) x <- replicate(n = 5, 'left') y <- replicate(n = 5, 'right') dir <- c(x,y) quantity <- sample(seq(1,100), 10) names <- rep(letters[1:5],2) tb <- tibble(dir,quantity,names) %>% group_by(dir) %>% mutate(names = fct_reorder(names, -quantity)) # 按quantity降序排列names tb %>% ggplot(aes(x = names, quantity)) + geom_bar(stat = 'identity', color = 'black') + coord_flip() + facet_wrap(~dir, scales = "free")
方法2:分组排序后手动设置因子水平
先分组按quantity降序排列,再把names转为因子,水平用分组内排序后的唯一值:
tb <- tibble(dir,quantity,names) %>% group_by(dir) %>% arrange(desc(quantity)) %>% mutate(names = factor(names, levels = unique(names))) # 用分组内排序后的顺序作为因子水平 tb %>% ggplot(aes(x = names, quantity)) + geom_bar(stat = 'identity', color = 'black') + coord_flip() + facet_wrap(~dir, scales = "free")
两种方法都能让每个分面里的标签按对应quantity从大到小排列,满足你的需求。
内容的提问来源于stack exchange,提问作者AColoredReptile
相关产品推荐
相关产品推荐

