简体   繁体   中英

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?

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. 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

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:

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 + . Feels a bit hacky, but generates this:

点和箱线图在同一轴上

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM