如何使用R绘制多个方框图
这是我的数据集的头部如何使用R绘制多个方框图,r,ggplot2,boxplot,R,Ggplot2,Boxplot,这是我的数据集的头部 ï..age sex cp trestbps chol fbs restecg thalach exang oldpeak slope ca thal 1 63 male 3 145 233 1 0 150 0 2.3 0 0 1 2 37 male 2 130 250 0 1 187 0 3.5 0 0
ï..age sex cp trestbps chol fbs restecg thalach exang oldpeak slope ca thal
1 63 male 3 145 233 1 0 150 0 2.3 0 0 1
2 37 male 2 130 250 0 1 187 0 3.5 0 0 2
3 41 female 1 130 204 0 0 172 0 1.4 2 0 2
4 56 male 1 120 236 0 1 178 0 0.8 2 0 2
5 57 female 0 120 354 0 1 163 1 0.6 2 0 2
6 57 male 0 140 192 0 1 148 0 0.4 1 0 1
target
1 yes
2 yes
3 yes
4 yes
5 yes
依赖变量是目标,我只想绘制数值变量的多框图(年龄、trestbps、thalach…),我想用依赖变量(目标)填充它,每个变量都必须用依赖变量填充。如何做到这一点?您可以使用以下代码
library(tidyverse)
df %>%
mutate_if(is.numeric,as.character, is.factor, as.character) %>%
pivot_longer(-target) %>%
filter(!((name == "sex"))) %>%
mutate(value = as.numeric(value)) %>%
ggplot(aes(x = target, y = value)) +
geom_boxplot() +
facet_wrap(name~., scales = "free")
资料
df这是否回答了您的问题?
df <- read.table(text = "age sex cp trestbps chol fbs restecg thalach exang oldpeak slope ca thal target
63 male 3 145 233 1 0 150 0 2.3 0 0 1 yes
37 male 2 130 250 0 1 187 0 3.5 0 0 2 yes
41 female 1 130 204 0 0 172 0 1.4 2 0 2 yes
56 male 1 120 236 0 1 178 0 0.8 2 0 2 yes
57 female 0 120 354 0 1 163 1 0.6 2 0 2 yes
57 male 0 140 192 0 1 148 0 0.4 1 0 1 yes", header =T)