r - scale_x_reordered 在facet_grid 中不起作用

标签 r facet-wrap facet-grid tidytext

我是 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")

enter image description here

从这张图表中,很难看出每年哪个州是最好的。因此,我决定每年使用 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()

enter image description here 但是,我无法像第一张图片中那样显示它。我以为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")

enter image description here

关于r - scale_x_reordered 在facet_grid 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71375393/

相关文章:

r - 更改facet_wrap多重图中的绘图标题大小

r - 使用 scales = 'free' 在 facet_wrap 中设置 x/y 限制

python - 在 Seaborn FacetGrid 图上绘制不同 'hue' 数据的平均线

r - 将带有 facet_grid 的 ggplot2 对象的标题移到中间

r - 如何在带 % 标签的填充条的多面 ggplot 中显示 'total'?

R:跳过在 CRAN R CMD 检查上运行的小插图

r - 我可以移动光标在 R 中修改吗?

r - 安全地通过函数 purrr 并保存出现错误的链接

r - 使用 dplyr 和 tidyverse 通过时间汇总总和

r - 如何分别格式化每个 ggplot 面板的轴刻度标签?