生成ggplot2中多个变量的箱线图而不进行分解 [英] Generate boxplots for multiple variables in ggplot2 without factoring
问题描述
添加了使用标准boxplot()函数生成的boxplot.
Added the boxplot generated with standard boxplot() function.
给出虹膜数据,以下代码:
Given the iris dataste, the following code:
boxplot(iris[,])
创建一个具有五个框的箱形图,每个变量一个,而不将它们分为种类(例如物种).尽管这很简单,但是我无法在ggplot2中做同样的事情.
Creates a boxplot with five boxes, one for each variable, without splitting them into categories such as, for instance, species. While this is simple enough, I have been unable to do the same in ggplot2.
那么我的问题很简单:我该如何实现?
My question, then, is simple: how can I achieve this?
推荐答案
种类
是一个具有三个级别的因素( setosa
, versicolor
和 virginica
).我认为如果将其与其他变量一起绘制是没有意义的.
Species
is a factor with three levels (setosa
, versicolor
and virginica
). I think it doesn't make sense if you plot it with the other variables.
如果要绘制所有其他4个变量( Sepal.Length
, Sepal.Width
, Petal.Length
,和 Petal.Width
)如下图所示
It makes more sense if you want to plot all other 4 variables (Sepal.Length
, Sepal.Width
, Petal.Length
, and Petal.Width
) in one plot as below
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()
如果要在同一图中绘制所有5个变量,则需要将 species
转换为数字
If you want to plot all 5 variables in the same plot, you need to convert species
to be numeric
iris %>% dplyr::mutate(Species = as.numeric(Species)) %>% tidyr::gather("id", "value",1:5) %>%
ggplot(., aes(x = id, y = value))+geom_boxplot()
这篇关于生成ggplot2中多个变量的箱线图而不进行分解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!