在ggplot2中为多个变量生成箱线图而不考虑因子

时间:2017-03-24 00:26:26

标签: r ggplot2

编辑:添加了使用标准boxplot()函数生成的boxplot。

鉴于iris dataste,以下代码:

boxplot(iris[,])

创建一个包含五个框的箱形图,每个框对应一个变量,而不将它们分成类别,例如物种。虽然这很简单,但我无法在ggplot2中做同样的事情。

Boxplot generated with standard function.

我的问题很简单:我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:2)

Species是一个包含三个级别(setosaversicolorvirginica)的因素。我认为如果你用其他变量绘制它是没有意义的。

如果您想在一个图中绘制所有其他4个变量(Sepal.LengthSepal.WidthPetal.LengthPetal.Width),则更有意义

library(dplyr)
library(tidyr)
library(ggplot2)
iris %>% dplyr::select(Species, everything()) %>% tidyr::gather("id", "value",2:5) %>% 
  ggplot(., aes(x = id, y = value))+geom_boxplot()

enter image description here

如果要在同一图中绘制所有5个变量,则需要将species转换为数字

iris %>% dplyr::mutate(Species = as.numeric(Species)) %>% tidyr::gather("id", "value",1:5) %>% 
  ggplot(., aes(x = id, y = value))+geom_boxplot()

enter image description here