首页 > 解决方案 > 在 ggplot2 的 aes() 中使用组参数

问题描述

我正在尝试在 ggplot2 的 aes() 中使用“组”参数,但我不确定为什么它不能像我目前拥有的那样工作。

我想要一个图像,以该图像使用“sex”的方式对我的“maskalthalf”变量进行分组(在此处找到)。

在此处输入图像描述

这就是我的图表目前的样子。

在此处输入图像描述

这是我到目前为止的代码。

ggplot(groups, aes(x = message, y = mean, group = factor(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)

这是我的目标的草图:

在此处输入图像描述

数据:

structure(list(maskalthalf = c("High", "High", "Low", "Low"), 
    message = c("General", "Personal", "General", "Personal"), 
    mean = c(4.79090909090909, 6.38181818181818, 4.69879518072289, 
    4.8433734939759), se = c(0.144452868727642, 0.104112130946133, 
    0.149182255019704, 0.180996951567937)), row.names = c(NA, 
-4L), groups = structure(list(maskalthalf = c("High", "Low"), 
    .rows = structure(list(1:2, 3:4), 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"))

标签: rggplot2graphbar-chart

解决方案


第一个示例中的图像使用构面按变量分组。所以你可以试试:

ggplot(df1, 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") + 
  ylab("Rating") + 
  xlab("Personal evaluation or general evaluation") + 
  ylim(0, 8) +
  facet_wrap(~maskalthalf)

在此处输入图像描述


推荐阅读