[英]How to superimpose 2 plots with same y-axis, but different x-axes in R
Is there a way to superimpose two plots with different x-axes? 有没有办法用不同的x轴叠加两个图?
I have a dataset with systolic blood pressure of a patient at different days when they were taking different medications. 我有一个数据集,其中包含患者在服用不同药物时不同天的收缩压。 I would like to create a scatterplot of their SBP by date, and superimpose a boxplot of their SBPs at each medication.
我想按日期创建其SBP的散点图,并在每种药物上叠加其SBP的箱线图。 I created the two plots separately but can't figure out how to combine them in one figure.
我分别创建了两个图,但无法弄清楚如何将它们组合成一个图。
library(ggplot2)
library(lubridate)
df <- data.frame(date = c(ymd("2014-09-01") + c(1:5), ymd("2014-09-11") + c(1:5), ymd("2014-09-21") + c(1:5)), sbp1 = round(runif(n=15, min=130, max=200)), group = c(rep("A",5), rep("B",5), rep("C", 5)))
p1 <- ggplot(df, aes(x=date, y=sbp1)) + geom_point(aes(color = group))
p2 <- ggplot(df, aes(x=group, y=sbp1)) + geom_boxplot(aes(x=group, y = sbp1))
p1
p2
You have to decide how to map the x coordinate into a single scale - eg like picking one date for the whole group: 您必须决定如何将x坐标映射到单个比例中-例如,像为整个组选择一个日期一样:
df %>%
group_by(group) %>%
mutate(groupdate = first(date) + 3) %>%
ggplot(aes(y = sbp1)) +
geom_boxplot(aes(x = groupdate, group = group)) +
geom_point(aes(x = date, colour = group))
Then you can superimpose ggplot geometries on top of each other by +
. 然后,您可以将ggplot几何图形彼此叠加
+
。 Feels a bit hacky, but generates this: 感觉有点骇人听闻,但是会生成以下内容:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.