【问题标题】:How to use long data for boxplot in R如何在 R 中使用长数据进行箱线图
【发布时间】:2020-03-29 15:18:17
【问题描述】:

我正在尝试为 3 个组的抑郁评分创建 3 个箱线图,在我的表中组织为长数据,如下所示:

   Ppt_num Depression_score Group   Age Gender
     <dbl>            <dbl> <dbl> <dbl>  <dbl>
 1       1                8     1    32      1
 2       2                4     1    45      2
 3       3               24     1    18      2
 4       4               11     1    45      1
 5       5               13     1    25      2
 6       6               14     1    67      2
 7       7               16     1    43      2
 8       8               11     1    25      1
 9       9                3     1    55      1
10      10               21     1    70      2
# ... with 80 more rows

当我使用时:

boxplot <- ggplot(mini, aes(x = Group, y = Depression_score, fill=Group)) + geom_boxplot()

它带有 1 个箱线图而不是 3 个,并且 x 轴被标记为 1.5、2.0、2.5。

当我尝试时:

boxplot<- ggplot(mini, aes(x = Group, y = Depression_score, fill=Group)) + geom_boxplot() + facet_grid(~Group)

我成功获得了 3 个箱线图,但除了在顶部由组号 (1、2、3) 分隔外,在每个箱线图的 x 轴上还有 1、2、3,所以第一个是1上面的左边,2上面中间的第二个,3上面右边的第三个,看起来有点奇怪。

我怎样才能让箱线图像使用 facet_grid 一样分开但不被分割两次?

【问题讨论】:

  • 试试ggplot(mini, aes(x = factor(Group), y = Depression_score, fill = factor(Group))) + geom_boxplot()。这会将 X 轴元素转换为因子,并且应该将它们分开。
  • 您包含的数据样本仅包含第 1 组的观察结果,因此我们将无法重现该问题

标签: r ggplot2 boxplot


【解决方案1】:

如果您想要与facet_wrap 相同的颜色,则需要将group=Group 添加到aes

data.table::fread("Ppt_num Depression_score Group   Age Gender
                         1                8     1    32      1
                         2                4     1    45      2
                         3               24     1    18      2
                         4               11     2    45      1
                         5               13     2    25      2
                         6               14     2    67      2
                         7               16     3    43      2
                         8               11     3    25      1
                         9                3     3    55      1
                        10               21     3    70      2") -> dt1


mini <- dplyr::as_tibble(dt1)

library(ggplot2)

ggplot(mini, aes(x = Group, y = Depression_score, fill=Group, group=Group)) + geom_boxplot()

【讨论】:

    猜你喜欢
    • 2013-07-15
    • 2017-05-25
    • 1970-01-01
    • 2021-12-04
    • 2015-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-08
    相关资源
    最近更新 更多