【问题标题】:How to do a three group boxplot in R with 3 columns of a dataframe?如何在 R 中用数据帧的 3 列绘制三组箱线图?
【发布时间】:2023-01-13 01:40:11
【问题描述】:

我正在计算 3 组的一些统计数据——所有、男性和女性。我将它们存储在一个名为 stats_df 的数据框中,每个组都作为列标题,统计数据作为行数据。我需要做一个 boxplot(我最近的尝试包含在代码中),将所有 3 个组都表示为框,但我似乎无法弄清楚,也没有在线教程提供帮助。数据:

代码:

all_stats <- c(all_mean, all_median, all_mode, all_25, all_50, all_75)
female_stats <- c(female_mean, female_median, female_mode, female_25, female_50, female_75)
male_stats <- c(male_mean, male_median, male_mode, male_25, male_50, male_75)

stats_df <- data.frame(all_stats, female_stats, male_stats)

boxplot(all_stats ~ male_stats,
        data=stats_df, 
        main="Stats Boxplot",
        xlab="Group", 
        ylab="Number")

【问题讨论】:

  • 请以代码形式提供示例数据而不是屏幕截图 - 我们无法将屏幕截图导入 R,所以就目前情况而言,您要求我们首先将您的数据按值复制到 R 中......请参阅@987654322 @ 有关如何执行此操作的更多信息。

标签: r ggplot2 boxplot


【解决方案1】:

您可以使用以下代码:

stats_df <- data.frame(all_stats = c(35.19, 32, 29, 26, 32, 50),
                       female_stats = c(36.23, 32, 32, 24, 32, 52),
                       male_stats = c(33.5, 32, 29, 28.5, 32, 39.5))

library(tidyverse)
stats_df %>%
  ggplot() +
  geom_boxplot(aes(x = "all_stats", y = all_stats)) +
  geom_boxplot(aes(x = "female_stats", y = female_stats)) +
  geom_boxplot(aes(x = "male_stats", y = male_stats)) +
  xlab("Group") +
  ylab("Number") +
  ggtitle("Stats Boxplot")

输出:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 2017-10-31
    相关资源
    最近更新 更多