📌  相关文章
📜  如何在 R 中使用 ggplot2 制作分组箱线图?

📅  最后修改于: 2022-05-13 01:55:37.017000             🧑  作者: Mango

如何在 R 中使用 ggplot2 制作分组箱线图?

在本文中,我们将讨论如何使用 ggplot2 包在 R 编程语言中制作分组箱线图。

箱线图帮助我们可视化比较不同连续或分类变量的定量数据的分布。箱线图由五个数字组成,有助于检测和删除数据集中的异常值。这五个汇总数字是最小值、第一四分位数、中位数、第三四分位数和最大值。

分组箱线图用于可视化具有多个子组的数据。此外,我们可以使用分组箱线图一次可视化三个变量,其中一个变量是数值,另外两个是分类变量。我们可以通过使用 R 中 ggplot 的颜色属性来可视化第四个变量。

首先,要使用 ggplot2 包在 R 中制作基本箱线图,我们使用 R 语言中的 geom_boxplot()函数。

句法:

例子:

这是使用 ggplot2 包的 geom_boxplot函数制作的基本箱线图。

R
# load library ggplot
library(ggplot2)
  
# Plot boxplot using ggplot function
# diamonds dataset used here is inbuilt in the R Language
plot <- ggplot(diamonds, aes(x=factor(cut), y=carat))+
     geom_boxplot()+
     theme( legend.position = "none" )
 
# print boxplot
plot


R
# load library ggplot
library(ggplot2)
  
# Plot boxplot using ggplot function
# diamonds dataset used here is inbuilt in the R Language
plot <- ggplot(diamonds, aes(x=factor(cut), y=carat, color = factor(color)))+
     geom_boxplot()+
     theme( legend.position = "none" )
 
# print boxplot
plot


R
# load library ggplot
library(ggplot2)
  
# Plot boxplot using ggplot function
# diamonds dataset used here is inbuilt in the R Language
plot <- ggplot(diamonds, aes(x=factor(cut), y=carat, color=factor(cut) ))+
     geom_boxplot()+
     theme( legend.position = "none" )+
     facet_wrap(~color, ncol=3)
 
# print boxplot
plot


输出:

创建分组箱线图

要将这个基本箱线图转换为分组箱线图,我们使用 ggplot2 包的 aes()函数的颜色属性。在这里,我们使用第三个变量作为参数颜色的值来将基本箱线图转换为分组箱线图。

句法:

参数

  • x是第一个分类变量
  • y是定量变量
  • z是第二个分类变量。

例子:

这是一个在 ggplot2 中按可变颜色分组的箱线图。示例中使用的 diamonds 数据集是用 R 语言预先构建的。

R

# load library ggplot
library(ggplot2)
  
# Plot boxplot using ggplot function
# diamonds dataset used here is inbuilt in the R Language
plot <- ggplot(diamonds, aes(x=factor(cut), y=carat, color = factor(color)))+
     geom_boxplot()+
     theme( legend.position = "none" )
 
# print boxplot
plot

输出:

带分面的分组箱线图

还有另一种方法可以使用 ggplot2 包在 R 语言中制作分组箱线图。就是在ggplot中使用facet。 ggplot2 中的 faceting 函数提供了一种通用解决方案,可以将数据按一个或多个变量拆分,并将数据子集绘制在一起。要创建分组箱线图,我们可以使用 facet_wrap()函数。

句法:

参数

  • x是第一个分类变量
  • y是定量变量
  • z是第二个分类变量

例子:

这是一个使用 facet_wrap()函数在 ggplot2 中按可变颜色分组的箱线图。示例中使用的 diamonds 数据集是用 R 语言预先构建的。我们还通过在 ggplot()函数中使用 cut 变量作为 color 参数的值来为绘图着色。

R

# load library ggplot
library(ggplot2)
  
# Plot boxplot using ggplot function
# diamonds dataset used here is inbuilt in the R Language
plot <- ggplot(diamonds, aes(x=factor(cut), y=carat, color=factor(cut) ))+
     geom_boxplot()+
     theme( legend.position = "none" )+
     facet_wrap(~color, ncol=3)
 
# print boxplot
plot

输出: