如何在ggplot2中按高低排序facet_wrap多折线分面图
如何按数值高低排序ggplot2的facet_wrap多折线分面图
我明白你遇到的问题了——单条形图的排序方法用熟了,但到了多折线的分面图就摸不着头脑,不知道怎么让分面按数值从高到低排列。其实核心思路很简单:分面的顺序完全由因子变量的水平顺序决定,只要我们重新调整Country这个因子的水平顺序,就能让分面按我们想要的方式排列。
咱们用你的示例数据来一步步解决:
核心方法:重新调整因子水平顺序
我们可以借助tidyverse里的forcats包(已包含在tidyverse中)的fct_reorder函数,快速根据指定数值列排序因子水平。
步骤1:处理数据,排序Country因子
你的数据是分组状态(grouped_df),先取消分组,然后用每个国家的mean值降序排列Country因子:
library(tidyverse) # 取消分组并重新排序Country因子 sorted_df <- example_df %>% ungroup() %>% # 按mean值降序排列Country因子 mutate(Country = fct_reorder(Country, mean, .desc = TRUE))
步骤2:用排序后的数据绘图
直接使用处理好的sorted_df绘图,分面就会自动按mean从高到低(Ecuador到U.A.E)排列:
sorted_df %>% ggplot(aes(x = Year, y = Tonnes_x1000, colour = Country)) + geom_line() + scale_colour_tableau() + scale_x_date(date_labels = "%y") + theme_minimal() + theme(legend.position = 0) + labs(x = "", y = "In 1000 Tonnes") + facet_wrap( ~ Country, ncol = 5)
可选:按指定年份的数值排序
如果你不想用mean,而是想用某一年的数值(比如最后一年的Tonnes_x1000)来排序,可以用下面的方法:
# 按最后一年的Tonnes_x1000降序排序Country sorted_df_by_year <- example_df %>% ungroup() %>% # 筛选出最后一年的数据 filter(Year == max(Year)) %>% # 按Tonnes_x1000降序排列 arrange(desc(Tonnes_x1000)) %>% # 提取排序后的Country列表 pull(Country) %>% # 将原数据的Country因子水平设置为这个排序后的列表 let(ordered_countries = ., example_df %>% mutate(Country = factor(Country, levels = ordered_countries))) # 绘图 sorted_df_by_year %>% ggplot(aes(x = Year, y = Tonnes_x1000, colour = Country)) + geom_line() + scale_colour_tableau() + scale_x_date(date_labels = "%y") + theme_minimal() + theme(legend.position = 0) + labs(x = "", y = "In 1000 Tonnes") + facet_wrap( ~ Country, ncol = 5)
内容的提问来源于stack exchange,提问作者Tdebeus
相关产品推荐
相关产品推荐

