具有多个因素分组的条形图和这些因素的变量平均值

Barplots with multiple factor groupings and mean of variable across those factors

我正在尝试创建一个条形图,显示按大学毕业生或非大学毕业生按单身或已婚分组的工会和非工会工人的平均小时工资。虽然我设法用两个因素分组构建了一个可以通过的条形图,但我无法弄清楚如何用三个因素分组来做到这一点。我看到的具有三个因素的示例仅关注频率计数,因此我不确定如何将所有因素中另一个变量的平均值合并到图中。我想要创建的东西看起来像这样(在 Stata 中创建): Average Hourly Wage by Union Status, Marital Status, and College Graduation 我的代码如下所示:

levelbar = tapply(wage, list(as.factor(union), as.factor(married), 
as.factor(collgrad)), mean)
par(mfrow = c(1, 2))
barplot(levelbar, beside = TRUE)
barplot(t(levelbar), beside = TRUE)

但是,当我 运行 执行此操作时,我收到错误消息:

Error in barplot.default(levelbar, beside = TRUE) : 
'height' must be a vector or a matrix

如有任何帮助,我们将不胜感激。我确定 ggplot 在这里可能会有用,但我没有太多使用该包的经验。

这是一个使用 ggplot 和内置数据集 Titanic 的可重现示例。

请注意,我们首先计算均值,然后使用 stat = identity 确保我们将它们纳入图中。

# Format the Titanic dataframe
Titanic_df <- Titanic %>% as_tibble()

# Make Class, Sex, Age, and Survived factors
for (col in c("Class", "Sex", "Age", "Survived")) {
  Titanic_df[[col]] <- factor(Titanic_df[[col]])
}

# Get by group means
means <- Titanic_df %>% 
  group_by(Class, Sex, Survived) %>% 
  summarise(
    mean_n = mean(n)
  )

# Plot: facets are the Classes, bar colors are the two Sexes, and the groupings in each facet are Survived vs. Not Survived
ggplot(data = means) +
  geom_bar(aes(x = Survived, y = mean_n, fill = Sex), stat = "identity", position = "dodge") +
  facet_wrap(~ Class)