r - 如何在r中的箱线图之间创建单独的线图
问题描述
我正在尝试创建如下图所示的图,其中各个数据线位于箱形图之间。在 R ggplot2 中创建的图像
我得到的最接近的是这样的: 使用 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()
任何提示将非常感谢!
解决方案
实现所需结果的一种选择是使用连续 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)
)
编辑如果您想并排放置两个箱线图,则基本相同。但是,在这种情况下,您必须将interaction
of和映射在美学上Time1
的变量映射到(可能还有误差线):fill
group
geom_boxplot
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()
推荐阅读
- php - PHP中的2路字符串加密 - 其中哪一个更安全?
- python - 在 Pandas 中计算字符串中单词的出现次数
- sql - 与其他列连接子查询
- javascript - 2D 平面图 JavaScript 库
- python - Python Selenium 问题:鼠标右键单击并拖动?
- sql - SQL 添加 Order By 子句会使查询运行得更快。需要解释
- opencv - 计算前向量并查看向量
- javascript - For-loop 仅运行 1 次 - JavaScript
- reactjs - 反应 - 写两次相同的测试第一次通过但不是第二次
- c# - Hangfire 没有以它被称为的方式执行作业?