[英]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.