[英]How to connect paired dots in dodged dotplots with ggplot2 in R?
我有几个变量测量了两次,我想将它们显示在一个图表中,显示箱线图以及单个值(使用geom_dotplot
),其中来自同一变量中的两个测量值的值通过可自定义的线连接。
我找到了一个使用geom_point
的解决方案(基本上生成一个新数据),但如果可能的话,我想要一个点图。
为 5 个主题和 2 个变量创建图表的简化代码
library(ggplot2)
dat <- data.frame(subject = c(1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5),
measurement = c("M1", "M1", "M1", "M1", "M1", "M2", "M2", "M2", "M2", "M2",
"M1", "M1", "M1", "M1", "M1", "M2", "M2", "M2", "M2", "M2"),
variable = c("Var1", "Var1", "Var1", "Var1", "Var1", "Var1", "Var1", "Var1", "Var1", "Var1",
"Var2", "Var2", "Var2", "Var2", "Var2", "Var2", "Var2", "Var2", "Var2", "Var2"),
value = c(20, 15, 21, 23, 15, 22, 21, 31, 24, 17, 26, 10, 23, 22, 19, 29, 15, 25, 29, 19))
ggplot(dat, aes(variable, value, colour = measurement)) +
geom_boxplot(outlier.shape = NA) +
geom_dotplot(aes(fill = measurement),
binaxis = "y", binwidth = 0.5, stackdir = "center",
position = position_dodge(0.75))
在当前图表中,我希望在变量内的两个测量值之间用线连接成对的红色和青色点,如我手工绘制的 Var1 所示:
谢谢,铅
您可以通过使用facet_wrap
并指定aes(group = subject)
来实现类似的 output ,因此每条灰线都是一个单独的主题。 我提供了两个选项,一个按变量拆分,另一个按测量拆分。 第二个 plot 可能更接近你最初的想法。
library(tidyverse)
dat <- data.frame(subject = c(1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5),
measurement = c("M1", "M1", "M1", "M1", "M1", "M2", "M2", "M2", "M2", "M2",
"M1", "M1", "M1", "M1", "M1", "M2", "M2", "M2", "M2", "M2"),
variable = c("Var1", "Var1", "Var1", "Var1", "Var1", "Var1", "Var1", "Var1", "Var1", "Var1",
"Var2", "Var2", "Var2", "Var2", "Var2", "Var2", "Var2", "Var2", "Var2", "Var2"),
value = c(20, 15, 21, 23, 15, 22, 21, 31, 24, 17, 26, 10, 23, 22, 19, 29, 15, 25, 29, 19))
# split by measurement
dat %>%
mutate(new = factor(interaction(measurement, variable))) %>%
ggplot(aes(x = new, y = value, color = measurement)) +
geom_boxplot(outlier.shape = NA) +
geom_dotplot(aes(fill = measurement),
binaxis = "y", binwidth = 0.5, stackdir = "center",
position = position_dodge(0.75)) +
geom_line(aes(group = subject), color = "gray") +
facet_wrap(~measurement, scales = "free") +
scale_x_discrete(labels = c("Var1", "Var2")) +
xlab("")
# split by variable
dat %>%
mutate(new = factor(interaction(variable, measurement))) %>%
ggplot(aes(x = new, y = value, color = variable)) +
geom_boxplot(outlier.shape = NA) +
geom_dotplot(aes(fill = variable),
binaxis = "y", binwidth = 0.5, stackdir = "center",
position = position_dodge(0.75)) +
geom_line(aes(group = subject), color = "gray") +
facet_wrap(~variable, scales = "free") +
scale_x_discrete(labels = c("M1", "M2")) +
xlab("")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.