如何在r中的箱线图之间创建单独的线图
Posted
技术标签:
【中文标题】如何在r中的箱线图之间创建单独的线图【英文标题】:How to create an individual line plot in between box plot in r 【发布时间】:2021-10-09 01:51:55 【问题描述】:我正在尝试创建如下图所示的图,其中各个数据线位于箱形图之间。 Image to create in R ggplot2
我得到的最接近的是这样的: Image using ggplot2 但后面的线/点看起来有点杂乱。
data1 %>%
ggplot(aes(Time,Trait)) +
geom_line(aes(group=ID), position = "identity")+
geom_point(aes(group=ID), shape=21, colour="black", size=2, position = "identity")+
geom_boxplot(width=.5,position = position_dodge(width=0.9), fill="white") +
stat_summary(fun.data= mean_cl_boot, geom = "errorbar", width = 0.1, position = position_dodge(width = .9)) +
stat_summary(fun = mean, geom = "point", shape = 18, size=3, position = "identity")+
facet_wrap(~Cond) +
theme_classic()
任何提示将不胜感激!
【问题讨论】:
你好埃里希,非常好的问题。你能发布你的部分数据吗? 以前的相关讨论-***.com/questions/15605926/… 【参考方案1】:实现您想要的结果的一个选择是使用连续的 x 比例。这样做可以使点和线的箱线图向左或向右移动,反之亦然:
利用一些随机数据来模拟你的真实数据集。
data1$Time1 <- as.numeric(factor(data1$Time, levels = c("Pre", "Post")))
data1$Time_box <- data1$Time1 + .1 * ifelse(data1$Time == "Pre", -1, 1)
data1$Time_lp <- data1$Time1 + .1 * ifelse(data1$Time == "Pre", 1, -1)
library(ggplot2)
ggplot(data1, aes(x = Time_box, y = Trait)) +
geom_line(aes(x = Time_lp, group=ID), position = "identity")+
geom_point(aes(x = Time_lp, group=ID), shape=21, colour="black", size=2, position = "identity")+
geom_boxplot(aes(x = Time_box, group=Time1), width=.25, fill="white") +
stat_summary(fun.data = mean_cl_boot, geom = "errorbar", width = 0.1) +
stat_summary(fun = mean, geom = "point", shape = 18, size=3, position = "identity") +
scale_x_continuous(breaks = c(1, 2), labels = c("Pre", "Post")) +
facet_wrap(~Cond) +
theme_classic()
数据
set.seed(42)
data1 <- data.frame(
ID = rep(1:10, 4),
Time = rep(c("Pre", "Post"), each = 10),
Trait = runif(40),
Cond = rep(c("MBSR", "SME"), each = 20)
)
编辑 如果您想并排放置两个箱线图,则基本相同。但是在这种情况下,您必须将Time1
的interaction
和映射在fill
上的变量映射到geom_boxplot
中的group
美学上(可能还有误差线):
library(ggplot2)
set.seed(42)
data1 <- data.frame(
ID = rep(1:10, 4),
Time = rep(c("Pre", "Post"), each = 10),
Fill = rep(c("Fill1", "Fill2"), each = 5),
Trait = runif(40),
Cond = rep(c("MBSR", "SME"), each = 20)
)
ggplot(data1, aes(x = Time_box, y = Trait)) +
geom_line(aes(x = Time_lp, group=ID, color = Fill), position = "identity")+
geom_point(aes(x = Time_lp, group=ID, fill = Fill), shape=21, colour="black", size=2, position = "identity")+
geom_boxplot(aes(x = Time_box, group=interaction(Time1, Fill) , fill = Fill), width=.25) +
stat_summary(fun.data = mean_cl_boot, geom = "errorbar", width = 0.1) +
stat_summary(fun = mean, geom = "point", shape = 18, size=3, position = "identity") +
scale_x_continuous(breaks = c(1, 2), labels = c("Pre", "Post")) +
facet_wrap(~Cond) +
theme_classic()
【讨论】:
非常感谢您的快速响应!非常有帮助。效果很好!现在,如果我想为每个前/后添加另一个箱线图(填充组)(所以它出现在图例中),我该怎么做? position_dodge 似乎不适用于箱线图... 基本上是一样的。但是您必须设置group
ing 权限才能使其正常工作。以上是关于如何在r中的箱线图之间创建单独的线图的主要内容,如果未能解决你的问题,请参考以下文章