使用forcat :: fct_reorder对facet_wrap中的绘图进行排序

时间:2016-11-02 14:06:44

标签: r ggplot2 facet

随着时间的推移,我有国家级统计数据。我使用facet_wrap()按国家/地区绘图,但我想根据最新值(2015)按降序排列图表。我曾尝试使用transform(),但只对第一个值(2005)进行排序。我认为forcats::fct_reorder()可以帮助我,但我没有成功插入facet_wrap()的任何参数。这甚至可能吗?如果可能,我宁愿不必grid_arrange() as this question suggests

Country <- c('a', 'b', 'c', 'x', 'y', 'z')
`2005` <- c(500, 700, 600, 900, 800, 1000)
`2010` <- c(900, 600, 800, 1000, 500, 700)
`2015` <- c(1000, 900, 500, 800, 700, 600)

df1 <- data.frame(Country, `2005`, `2010`, `2015`)

gather1 <- gather(df1, "Year", myValue, 2:4)

gg1 <- ggplot() +
  geom_line(data = gather1, aes(x = Year, y = myValue, group = Country), size = 1.5, color = "orange") +
  facet_wrap(~ Country, ncol = 3) +
  theme(aspect.ratio = (35/50))
gg1

1 个答案:

答案 0 :(得分:3)

你走了!

gather2 <- df1 %>%
    mutate(Country=fct_reorder(Country, `2015`)) %>%
    gather("Year", myValue, 2:4)

gg2 <- ggplot() +
  geom_line(data = gather2, aes(x = Year, y = myValue, group = Country), size = 1.5, color = "orange") +
  facet_wrap(~ Country, ncol = 3) +
  theme(aspect.ratio = (35/50))
gg2

enter image description here