同一图中四个变量的箱线图

Boxplots of four variables in the same plot

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

我正在使用众所周知的 Iris 数据集,我只想制作一个图表,其中包含 sepal.length、[=21= 的值的箱线图]、petal.length 和 petal.width 彼此相邻。这些都是数值。

我觉得这应该很简单,但我正在努力弄清楚这一点。

如有任何帮助,我们将不胜感激。

试试这个。该方法是选择数值变量并使用 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()

输出:

base R中,在one-liner

中可以更容易地完成
boxplot(iris[-5])


或使用 ggpubr

中的 ggboxplot
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"))

这是 one-liner 使用 reshape2::melt

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