r - 当存在重复值时,重新排序 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"))
解决方案
您可以使用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)
推荐阅读
- c# - 为什么尝试加载 System.Configuration.AppSettingsSection 配置部分失败?
- python - 无法使用 psycopg2 创建 citext 列
- reactjs - 如何在 React Native 中使用开/关按钮将数组项显示到列表中?
- r - 将 sjPlot::tab_model() 或其他 html 表格的输出编织到 PDF 文档中
- javascript - 使用标题破坏
- html - 建立外部链接和防止诈骗投诉的正确方法
- amazon-web-services - 将多个文件写入 S3 作为备份并处理最终一致性
- ios - 导出 .framework 时如何包含 Cocoapods 依赖项?
- .net-core - 如何在 Visual Studio for Mac 中解决 DLLNotFoundException
- javascript - 单元测试 POST HTTP 请求 - 如何期望随请求一起发送的对象成为 api URL 的一部分