使用 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()
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
给你!
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
我有一段时间内的国家级统计数据。我使用 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
给你!
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