我是 R 新手,想寻求您关于使用 reorder_within 和 scale_x_reordered(库:tidytext)进行可视化的建议。
我想按州显示每年的数据(按最大到最小排序)。这是用于说明目的的示例数据。
test <- data.frame(stateabb = rep(state.abb, each = 5, times = 1),
year = seq(2001,2005,1),
value = sample(1:100, 250, replace = TRUE))
我使用以下代码成功地按州和年份创建了简单的图表。
ggplot(test, aes(x = stateabb, y = value)) +
geom_bar(stat = "identity") +
facet_grid(year ~ ., scales = "free_x")
从这张图表中,很难看出每年哪个州是最好的。因此,我决定每年使用 reorder_within 对值进行排序。
ggplot(test, aes(x = reorder_within(stateabb, -value, year), y = value)) +
geom_bar(stat = "identity") +
facet_grid(year ~ ., scales = "free_x") +
scale_x_reordered()
但是,我无法像第一张图片中那样显示它。我以为scale_x_reordered可以解决这个问题,但结果并没有达到我的预期。我还了解到,我需要将 x 轴设置为空闲,以便显示每年各州的顺序。但这样做对我没有任何帮助。我在这里做错了什么?有没有其他合适的方法来按年份显示这些州的顺序?任何正确显示此图表的建议或建议将不胜感激。提前非常感谢!
最佳答案
这是行不通的,因为 facet_grid
只有一个共享的 x 轴。但各个方面的顺序都不同。您需要facet_wrap
。例如这样:
library(ggplot); library(tidytext)
ggplot(test, aes(x = reorder_within(stateabb, -value, year), y = value)) +
geom_bar(stat = "identity") + scale_x_reordered() +
facet_wrap(year ~ ., ncol = 1, scales = "free_x", strip.position = "right")
关于r - scale_x_reordered 在facet_grid 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71375393/