在 R 中使用 fct_relevel 和 ggplot 重新排序变量

Reordering variables using fct_relevel with ggplot in R

我正在尝试使用 fct_relevel() 对图表中的变量重新排序。我试过将列更改为一个因素。我不确定为什么我的代码不起作用。我需要“拥有的面板”显示在“不拥有的面板”前面。我也对不依赖 fct_relevel().

的替代方案持开放态度

图码:

groups %>%
  mutate(panels = fct_relevel(panels), "Owned Panels", "Did Not Own Panels") %>%
ggplot(., aes(x=reason, y = mean, fill = panels)) + 
  geom_bar(stat = "identity", color = "black", position = position_dodge()) +
  geom_errorbar(aes(ymin = mean - se, ymax = mean+se), width = .2, position = position_dodge(.9)) +
  geom_text(aes(label = round(mean, digits =2)), position = position_dodge(width=1.0), vjust = -1.5) +
  #facet_wrap(~dv) +
  labs(title = ~ "Likelihood of solar panel installation after meeting ambassador", 
       y = "Likelihood of installing solar panels", 
       x = "Reason to install solar panels") + 
  scale_fill_discrete(name = "Ambassador solar\npanel ownership") + 
  scale_y_continuous(limits = c(1, 7), oob = scales::oob_squish) 

数据:

structure(list(dv = c("behavior", "behavior", "behavior", "behavior"
), panels = c("Owned Panels", "Owned Panels", "Did Not Own Panels", 
"Did Not Own Panels"), reason = c("Environment", "Money", "Environment", 
"Money"), mean = c(5.15789473684211, 5.36065573770492, 4.85454545454545, 
4.35483870967742), se = c(0.224988824122626, 0.194223670966034, 
0.187878787878788, 0.210884132880012)), row.names = c(NA, -4L
), groups = structure(list(dv = c("behavior", "behavior"), panels = c("Did Not Own Panels", 
"Owned Panels"), .rows = structure(list(3:4, 1:2), ptype = integer(0), class = c("vctrs_list_of", 
"vctrs_vctr", "list"))), row.names = 1:2, class = c("tbl_df", 
"tbl", "data.frame"), .drop = TRUE), class = c("grouped_df", 
"tbl_df", "tbl", "data.frame"))

在 OP 的代码中,fct_relevel 在指定级别之前关闭

library(forcats)
library(dplyr)
library(ggplot2)
groups %>%
    mutate(panels = fct_relevel(panels), "Owned Panels", "Did Not Own Panels")
                                      ^                                        

相反,它会是(也 ungroup 在这样做之前)

groups %>% 
   ungroup %>% 
   mutate(panels =  fct_relevel(panels, "Owned Panels", "Did Not Own Panels") )    %>%
 ggplot(., aes(x=reason, y = mean, fill = panels)) + 
  geom_bar(stat = "identity", color = "black", position = position_dodge()) +
  geom_errorbar(aes(ymin = mean - se, ymax = mean+se), width = .2, position = position_dodge(.9)) +
  geom_text(aes(label = round(mean, digits =2)), 
      position = position_dodge(width=1.0), vjust = -1.5) +
  #facet_wrap(~dv) +
  labs(title = ~ "Likelihood of solar panel installation after meeting ambassador", 
       y = "Likelihood of installing solar panels", 
       x = "Reason to install solar panels") + 
  scale_fill_discrete(name = "Ambassador solar\npanel ownership") + 
  scale_y_continuous(limits = c(1, 7), oob = scales::oob_squish)