我想为包含四个类别的数据集绘制箱形图,例如:良好,不良,非常好和非常不良以及四个正态分布。 我的问题是如何在一个绘图中使四个类别具有四个不同的正态分布的绘图彼此分离,我试过了(见下文),但看起来一团糟。 我使用了一个示例,在这里找到它并对其进行了一些更改。 我添加了另一个编辑后的图,我希望箱形图的每个图看起来都像这样,它更加夹板,并且每四个类别(蓝色,黄色,红色和绿色)都清晰可见。
par(mfrow=c(2,2))
df <- data.frame(id = c(rep("Good",200), rep("Bad", 200),
rep("VeryGood",200), rep("VeryBad",200)),
F1 = c(rnorm(200,10,2), rnorm(200,8,1), rnorm(200,5,2),rnorm(200,7,3)),
F2 = c(rnorm(200,7,1), rnorm(200,6,1), rnorm(200,8,1),rnorm(200,12,4)),
F3 = c(rnorm(200,6,2), rnorm(200,9,3),rnorm(200,12,3),rnorm(200,15,2)),
F4 = c(rnorm(200,12,3), rnorm(200,8,2),rnorm(200,8,5),rnorm(200,5,1)))
boxplot(df[,-1], xlim = c(0.5, ncol(df[,-1])+0.9),
boxfill=rgb(1, 1, 1, alpha=1), border=rgb(1, 1, 1, alpha=1)) #invisible boxes
boxplot(df[which(df$id=="Good"), -1], xaxt = "n", add = TRUE, boxfill="red", boxwex=0.25,
at = 1:ncol(df[,-1]) - 0.15) #shift these left by -0.15
boxplot(df[which(df$id=="Bad"), -1], xaxt = "n", add = TRUE, boxfill="blue", boxwex=0.25,
at = 1:ncol(df[,-1]) + 0.15) #shift these right by +0.15
boxplot(df[which(df$id=="VeryBad"), -1], xaxt = "n", add = TRUE, boxfill="green", boxwex=0.25,
at = 1:ncol(df[,-1]) + 0.25) #shift these right by +0.15
boxplot(df[which(df$id=="VeryGood"), -1], xaxt = "n", add = TRUE, boxfill="yellow", boxwex=0.25,
at = 1:ncol(df[,-1]) + 0.45) #shift these right by +0.15
答案 0 :(得分:1)
如果您不打算使用Base R图形,而是查看添加到问题中的新绘图,我相信这就是您要寻找的内容:
library(dplyr)
library(tidyr)
library(ggplot2)
df <- data.frame(id = c(rep("Good",200), rep("Bad", 200),
rep("VeryGood",200), rep("VeryBad",200)),
F1 = c(rnorm(200,10,2), rnorm(200,8,1), rnorm(200,5,2),rnorm(200,7,3)),
F2 = c(rnorm(200,7,1), rnorm(200,6,1), rnorm(200,8,1),rnorm(200,12,4)),
F3 = c(rnorm(200,6,2), rnorm(200,9,3),rnorm(200,12,3),rnorm(200,15,2)),
F4 = c(rnorm(200,12,3), rnorm(200,8,2),rnorm(200,8,5),rnorm(200,5,1)))
df2 <- tidyr::gather(df, key = "FVar", value = "value", F1:F4)
df2 %>%
ggplot(aes(id, value, fill = id)) +
geom_boxplot() +
facet_grid(. ~ FVar) +
theme(axis.text.x = element_text(angle = 90, hjust = 0.5, vjust = 0.5))