代码之家  ›  专栏  ›  技术社区  ›  w5698

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

  •  0
  • w5698  · 技术社区  · 3 年前

    我正在构建一个组条形图。以下是我迄今为止编写的代码:

    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))
    

    这将产生以下曲线图: enter image description here

    总体而言,我对这一点感到满意,但我希望两个小节的顺序发生变化:危机前应该先于危机后。有人知道如何解决这个问题吗?任何帮助都将不胜感激。以下是一个可重复性最低的示例的数据:

    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")
    
    1 回复  |  直到 3 年前
        1
  •  1
  •   stefan    3 年前

    一种选择是转换为使用 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))