【问题标题】:Boxplots of four variables in the same plot同一图中四个变量的箱线图
【发布时间】:2021-01-01 11:06:10
【问题描述】:

我想使用 ggplot2 并排制作四个箱线图,但我很难找到适合我目的的解释。

我正在使用著名的 Iris 数据集,我只想制作一个图表,其中包含 sepal.length、sepal.width、petal.length 和 petal 值的箱线图。宽度彼此相邻。这些都是数值。

我觉得这应该很简单,但我正在努力解决这个问题。

任何帮助将不胜感激。

【问题讨论】:

  • 这让我想起了我的第一个问题:Do I really need to reshape this wide data to use ggplot2?。基本上,答案是肯定的:ggplot 非常适用于长数据,如果您的数据很宽,那么第一步就是让它变长。 tidyr::pivot_longer 是完成这项工作的好工具。

标签: r ggplot2 iris-dataset


【解决方案1】:

base R中,可以更轻松地在单行中完成

boxplot(iris[-5])


或者使用来自ggpubrggboxplot

library(ggpubr)
library(dplyr)
library(tidyr)
iris %>% 
  select(-Species) %>%
  pivot_longer(everything()) %>% 
  ggboxplot(x = 'name', fill = "name", y = 'value', 
      palette = c("#00AFBB", "#E7B800", "#FC4E07", "#00FABA"))

【讨论】:

    【解决方案2】:

    这是一个使用reshape2::melt的单行代码

    ggplot(reshape2::melt(iris), aes(variable, value, fill = variable)) + geom_boxplot()
    

    【讨论】:

    • 谢谢,这正是我想要的!我最近才发现 reshape2,还在学习术语。
    【解决方案3】:

    试试这个。该方法是选择数字变量并使用tidyverse 函数将其整形为 long 以绘制所需的图。您可以使用facet_wrap() 来创建矩阵样式图或避免它只有一个图。这里的代码(两个选项):

    library(tidyverse)
    #Data
    data("iris")
    #Code
    iris %>% select(-Species) %>%
      pivot_longer(everything()) %>%
      ggplot(aes(x=name,y=value,fill=name))+
      geom_boxplot()+
      facet_wrap(.~name,scale='free')
    

    输出:

    或者,如果您想将所有数据集中在一个图中,您可以避免使用 facet_wrap() 并使用以下代码:

    #Code 2
    iris %>% select(-Species) %>%
      pivot_longer(everything()) %>%
      ggplot(aes(x=name,y=value,fill=name))+
      geom_boxplot()
    

    输出:

    【讨论】:

      猜你喜欢
      • 2020-06-02
      • 1970-01-01
      • 1970-01-01
      • 2021-02-28
      • 2023-01-31
      • 2018-10-22
      • 2016-10-18
      • 1970-01-01
      • 2021-11-01
      相关资源
      最近更新 更多