如何翻转分组条形图中条形的顺序?

How to flip order of bars in a grouped bar chart?

我正在构建组条形图。这是我到目前为止编写的代码:

p <- ggplot(data, aes(x = Word, y = Estimate, fill = Group)) +
  geom_col(position = "dodge") +
  geom_errorbar(
    aes(ymin = Estimate - SE, ymax = Estimate + SE),
    position = position_dodge(.9),
    width = .2
  ) + labs(x = "Focal Word", y = "Norm of Beta Coefficients", title = "Figure 1: Results of Context Embedding Regression Model", caption = "p.")

p + theme(axis.text.x  = element_text(angle = 90))

这会产生以下图:

总体上我很满意,但我希望翻转条形图的顺序:危机前应该出现在 post-危机之前。有谁知道如何解决这个问题?任何帮助,将不胜感激。以下是可重现性最低的示例的数据:

structure(list(Word = c("Economy", "Economy", "Civil Rights", 
"Civil Rights", "Health", "Health"), Group = c("Pre-Crisis", 
"Post-Crisis", "Pre-Crisis", "Post-Crisis", "Pre-Crisis", "Post-Crisis"
), Estimate = c(0.08197375, 0.07068641, 0.3041591, 0.4429921, 
0.09703231, 0.1558241), SE = c(0.006251288, 0.003762346, 0.04490241, 
0.06448664, 0.01176194, 0.01211825)), row.names = c(NA, 6L), class = "data.frame")

一种选择是转换为使用 forcats::fct_rev,它会转换为因数并反转 Group 列的顺序:

library(ggplot2)

p <- ggplot(data, aes(x = Word, y = Estimate, fill = forcats::fct_rev(Group))) +
  geom_col(position = "dodge") +
  geom_errorbar(
    aes(ymin = Estimate - SE, ymax = Estimate + SE),
    position = position_dodge(.9),
    width = .2
  ) +
  labs(x = "Focal Word", y = "Norm of Beta Coefficients", title = "Figure 1: Results of Context Embedding Regression Model", caption = "p.")

p + theme(axis.text.x = element_text(angle = 90))