首页 > 解决方案 > 当存在重复值时,重新排序 ggplot 中的构面

问题描述

我正在尝试重新组织 facet_wrap 中“方面”的顺序。当有重复的变量名时,我该怎么做?

我尝试使用如下代码:

df$facet = factor(df$Case, levels = c("L", "B", "R", "BC"))

但是,这在我的情况下似乎不起作用,因为我在“maskalthalf”中有两个“高”和两个“低”,如下所示:

在此处输入图像描述

我也尝试过重新排序数据框本身的值,但 ggplot 将事物重新按字母顺序排列。

这是我的目标的草图:

在此处输入图像描述

这是我目前拥有的:

在此处输入图像描述

图表的当前代码:

ggplot(groups, aes(x = message, y = mean, group = factor(maskalthalf), fill = maskalthalf)) + 
  geom_bar(stat = "identity", width = 0.5, fill = "003900") +
  geom_text(aes(label = round(mean, digits = 1), vjust = -2)) + 
  geom_errorbar(aes(ymin = mean - se, ymax = mean + se), width = .2, position = position_dodge(.9)) + 
  labs(title = "Evaluations of Personal and General Convincingness") + 
  ylab("Rating") + 
  xlab("Personal evaluation or general evaluation") + 
  ylim(0, 8) + 
  facet_wrap(~maskalthalf)

数据:

dput(groups)
structure(list(maskalthalf = c("Low", "Low", "High", "High"), 
    message = c("General", "Personal", "General", "Personal"), 
    mean = c(4.69879518072289, 4.8433734939759, 4.79090909090909, 
    6.38181818181818), se = c(0.149182255019704, 0.180996951567937, 
    0.144452868727642, 0.104112130946133)), row.names = c(NA, 
-4L), groups = structure(list(maskalthalf = c("High", "Low"), 
    .rows = structure(list(3:4, 1:2), ptype = integer(0), class = c("vctrs_list_of", 
    "vctrs_vctr", "list"))), row.names = c(NA, -2L), class = c("tbl_df", 
"tbl", "data.frame"), .drop = TRUE), class = c("grouped_df", 
"tbl_df", "tbl", "data.frame"))

标签: rggplot2graphbar-chart

解决方案


您可以使用fct_relevel,但首先取消分组数据框。

library(forcats)
library(ggplot2)
library(dplyr)

groups %>% 
  ungroup() %>% 
  mutate(message = fct_relevel(message, "Personal", "General"),
         maskalthalf = fct_relevel(maskalthalf, "Low", "High")) %>% 
  ggplot(aes(x = message, y = mean)) + 
  geom_col(width = 0.5, fill = "003900") +
  geom_text(aes(label = round(mean, digits = 1), vjust = -2)) + 
  geom_errorbar(aes(ymin = mean - se, ymax = mean + se), width = .2, position = position_dodge(.9)) + 
  labs(title = "Evaluations of Personal and General Convincingness",
       y = "Rating",
       x = "Personal evaluation or general evaluation") + 
  ylim(0, 8) +
  facet_wrap(~maskalthalf)

在此处输入图像描述


推荐阅读