[英]How to plot multiple boxplot in one graph for R 2020
我有一些数据,需要在一张图中制作多个箱线图。 对于 Rstudio 3.6.1,没有 ggplot。 请使用可用的软件包。 数据文件是 csv,有 740 行。 在这里,我削减了前 20 行。
Absenteeism.time.in.hours Social.smoker Social.drinker
1 4 0 1
2 0 0 1
3 2 0 1
4 4 1 1
5 2 0 1
6 2 0 1
7 8 0 1
8 4 0 1
9 40 0 1
10 8 0 0
11 8 0 1
12 8 0 1
13 8 0 1
14 1 0 1
15 4 0 1
16 8 0 1
17 2 0 1
18 8 1 1
19 8 0 0
20 2 1 0
只使用boxplot
什么问题? 没有ggplot2
,这也应该适用于您的版本。
但是,“一张图中的多个箱线图”的含义并不明确。 这里有三个版本:
## by social group
op <- par(mfrow=c(1, 2)) ## set par
boxplot(Absenteeism.time.in.hours ~ Social.smoker, dat)
boxplot(Absenteeism.time.in.hours ~ Social.drinker, dat)
par(op) ## reset par
## by social group in one panel
datl <- reshape(dat, varying=2:3, direction="long")
boxplot(Absenteeism.time.in.hours ~ time + Social, datl)
## social group interaction
boxplot(Absenteeism.time.in.hours ~ ., dat)
数据:
dat <- read.table(header=T, text=" Absenteeism.time.in.hours Social.smoker Social.drinker
1 4 0 1
2 0 0 1
3 2 0 1
4 4 1 1
5 2 0 1
6 2 0 1
7 8 0 1
8 4 0 1
9 40 0 1
10 8 0 0
11 8 0 1
12 8 0 1
13 8 0 1
14 1 0 1
15 4 0 1
16 8 0 1
17 2 0 1
18 8 1 1
19 8 0 0
20 2 1 0")
@jay.sf 的解决方案非常棒(我相信他将是唯一一个在没有ggplot2
的世界中以惊人的可视化生存的人)。 正如伟大的@r2evans 在评论中提到的,让ggplot2
工作的关键是重塑数据。 一种方法是像您一样使用reshape2
函数。 但是使用实际的tidyverse
函数更容易将数据分析管道直接连接到视觉输出中。 在这里,我将包括一种使用tidyverse
使用pivot_wider()
将数据重塑为 long 并使用pivot_wider()
设置绘图的ggplot2
。 如果您想要多个图,您可以使用facet_wrap()
为您的图提供矩阵样式。 这里使用变量Absenteeism.time.in.hours
作为关键的代码以重塑其他二进制变量:
library(tidyverse)
#Code
dat %>% pivot_longer(cols = -Absenteeism.time.in.hours) %>%
ggplot(aes(x=factor(value),y=Absenteeism.time.in.hours))+
geom_boxplot()+
facet_wrap(.~name,scales = 'free')+
theme_bw()+
xlab('Var')
输出:
这种代码所产生得益于数据dat
由@ jay.sf(所有学分的数据管理给他)处理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.