Use forcat::fct_reorder to sort plots within facet_wrap

可紊 提交于 2019-12-11 01:32:37

问题


I have data with Country level stats over time. I use facet_wrap() to plot by Country but I want to order the plots based on only the most recent value (2015) in descending order. I've tried to use transform() but that orders only on the first values (2005). I think forcats::fct_reorder() could get me there but I have not been successful in inserting in any of the arguments for facet_wrap(). Is this even possible? I'd prefer not to have to do a grid_arrange() as this question suggests if possible.

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:


Here you go!

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



来源:https://stackoverflow.com/questions/40381987/use-forcatfct-reorder-to-sort-plots-within-facet-wrap

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!