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

使用fct_relevel和R中的ggplot对变量重新排序,r,ggplot2,graph,reorderlist,R,Ggplot2,Graph,Reorderlist,我试图使用fct_relevel()对图形中的变量重新排序。我已尝试将列更改为因子。我不确定为什么我的代码不起作用。我需要“拥有的面板”出现在“没有拥有的面板”前面。我也愿意接受不依赖fct_relevel()的替代方案 图形代码: groups %>% mutate(panels = fct_relevel(panels), "Owned Panels", "Did Not Own Panels") %>% ggplot(., aes(

我试图使用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) 
数据:


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

library(forcats)
library(dplyr)
library(ggplot2)
groups %>%
    mutate(panels = fct_relevel(panels), "Owned Panels", "Did Not Own Panels")
                                      ^                                        
相反,它将是(在执行此操作之前,也将
解组


为什么需要解组()?@melbez原因是如果有组,那么
fct\u relevel
无法在该组中找到某些级别(因为其中一些级别只有元素),因为您显示的dput具有
面板
作为
字符
类。根据代码,我们在绘图之前不进行任何分组汇总活动。因此,取消分组是安全的
library(forcats)
library(dplyr)
library(ggplot2)
groups %>%
    mutate(panels = fct_relevel(panels), "Owned Panels", "Did Not Own Panels")
                                      ^                                        
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)