使用forcat :: fct_reorder对facet_wrap中的图进行排序 [英] Use forcat::fct_reorder to sort plots within facet_wrap
问题描述
随着时间的推移,我掌握了具有国家/地区级统计信息的数据.我使用facet_wrap()
按国家(地区)进行绘图,但我想仅基于降序排列的最新值(2015)对绘图进行排序.我尝试使用transform()
,但是仅在第一个值(2005)上排序.我认为forcats::fct_reorder()
可以使我到达那里,但我没有成功插入facet_wrap()
的任何参数.这有可能吗?我希望不必执行grid_arrange()
此问题表明.
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
推荐答案
去这里!
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
这篇关于使用forcat :: fct_reorder对facet_wrap中的图进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!