【问题标题】:Problems with creating a boxplot using ggplot使用 ggplot 创建箱线图的问题
【发布时间】:2022-12-15 23:55:39
【问题描述】:

我正在尝试使用 ggplot(data, aes(x, y)) + geom_boxplot 创建箱线图,但我一开始就遇到了问题。我的数据看起来与此类似:

    S1   S2   S3   S4   
1   4.28 4.34 4.39 4.29
2   4.13 4.11 4.62 4.91
3   4.39 4.47 4.45 4.98
4   4.09 4.98 4.18 4.01
5   4.93 4.11 4.21 4.31
6   4.26 4.15 4.62 4.04
7   4.20 4.89 4.99 4.32
8   4.19 4.16 4.76 4.89
9   4.13 4.64 4.27 4.94
10  4.20 4.87 4.47 4.05
11  4.22 4.18 4.57 4.75
12  4.23 4.08 4.27 4.41
13  4.26 4.25 4.23 4.39
14  4.23 4.01 4.26 4.17
15  4.46 4.19 4.92 4.16
16  4.27 4.15 4.50 4.85
17  4.06 4.42 4.57 4.37
18  4.14 4.36 4.47 4.47
19  4.43 4.21 4.11 4.67
20  4.29 4.15 4.56 4.26

箱线图应在 x 轴上显示五个不同的物种,在 y 轴上显示值。

不幸的是,每次我将带有物种 (species <- colnames(data)) 的 aes(x,y) 定义为 x 时,我都会收到错误消息:!美学必须是长度 1 或与数据 (20) 相同:x。此外,我不知道 y 到底使用什么以及如何编码,因为我是 R 的新手。 我还使用 tidyr 包中的 pivot_longer 将数据重塑为长格式,就像另一个问题中建议的那样。但是,这也不会产生箱线图。 如果我使用基本的boxplot(),结果很好,但我需要用 ggplot 在视觉上增强箱线图。 我非常感谢所有能提供帮助的人!

【问题讨论】:

    标签: r ggplot2 boxplot


    【解决方案1】:

    你走在正确的轨道上。如果您的数据框名为data,您可以这样做:

    library(tidyverse)
    
    data %>%
      pivot_longer(everything(), names_to = 'Species') %>%
      ggplot(aes(Species, value)) +
      geom_boxplot()
    

    或者,如果你想变得花哨,

    df %>%
      pivot_longer(everything(), names_to = 'Species') %>%
      ggplot(aes(Species, value, color = Species)) +
      geom_point(position = position_jitter(width = 0.1), alpha = 0.5) +
      geom_boxplot(fill = NA, outlier.color = NA) +
      theme_minimal(base_size = 20) +
      scale_color_brewer(palette = 'Set1')
    

    创建于 2022-12-15 reprex v2.0.2


    可重现格式的数据

    data <- structure(list(S1 = c(4.28, 4.13, 4.39, 4.09, 4.93, 4.26, 4.2, 
    4.19, 4.13, 4.2, 4.22, 4.23, 4.26, 4.23, 4.46, 4.27, 4.06, 4.14, 
    4.43, 4.29), S2 = c(4.34, 4.11, 4.47, 4.98, 4.11, 4.15, 4.89, 
    4.16, 4.64, 4.87, 4.18, 4.08, 4.25, 4.01, 4.19, 4.15, 4.42, 4.36, 
    4.21, 4.15), S3 = c(4.39, 4.62, 4.45, 4.18, 4.21, 4.62, 4.99, 
    4.76, 4.27, 4.47, 4.57, 4.27, 4.23, 4.26, 4.92, 4.5, 4.57, 4.47, 
    4.11, 4.56), S4 = c(4.29, 4.91, 4.98, 4.01, 4.31, 4.04, 4.32, 
    4.89, 4.94, 4.05, 4.75, 4.41, 4.39, 4.17, 4.16, 4.85, 4.37, 4.47, 
    4.67, 4.26)), class = "data.frame", row.names = c("1", "2", "3", 
    "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", 
    "16", "17", "18", "19", "20"))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-07
      • 2017-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-10
      相关资源
      最近更新 更多