Generate boxplots for multiple variables in ggplot2 without factoring [duplicate]

不问归期 提交于 2021-02-08 05:42:07

问题


EDIT: Added the boxplot generated with standard boxplot() function.

Given the iris dataste, the following code:

boxplot(iris[,])

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?


回答1:


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.

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()

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()



来源:https://stackoverflow.com/questions/42990342/generate-boxplots-for-multiple-variables-in-ggplot2-without-factoring

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!