Reputation: 2307
I would like to plot two graph together which share the same x-axis. How can I do that? My data can be build using codes:
df <-structure(list(SDTM_LabN = c("ALP", "AST", "ALT", "AST", "ALT",
"ALT", "ALP", "AST", "ALP", "AST", "ALP", "ALT", "ALP", "ALP",
"ALT", "AST", "ALT", "ALT", "ALT", "AST", "AST", "ALP", "AST",
"ALT", "ALP", "ALP", "AST"), ADY = structure(c(45, 15, 1, 1,
30, 58, 30, 45, 46, -6, 23, 46, -6, 15, 23, 46, 45, -6, 8, 30,
58, 58, 23, 15, 8, 1, 8), class = "difftime", units = "days"),
result = c(0.841269841269841, 0.578947368421053, 0.625, 0.552631578947368,
0.416666666666667, 0.3125, 0.936507936507937, 0.447368421052632,
0.634920634920635, 0.657894736842105, 0.873015873015873,
0.291666666666667, 0.73015873015873, 0.857142857142857, 0.5,
0.447368421052632, 0.479166666666667, 0.625, 0.604166666666667,
0.5, 0.526315789473684, 0.849206349206349, 0.526315789473684,
0.5, 1.00793650793651, 0.896825396825397, 0.894736842105263
)), row.names = c(NA, -27L), class = "data.frame")
df2<-structure(list(ID = c(101, 101, 101, 101, 101, 101), AEDECOD = c("Diarrhoea",
"Vitreous floaters", "Musculoskeletal pain", "Diarrhoea", "Decreased appetite",
"Fatigue"), AESTDY = structure(c(101, 74, 65, 2, 33, 27), class = "difftime", units = "days"),
AEENDY = structure(c(105, 99, NA, 5, NA, NA), class = "difftime", units = "days")), row.names = c(NA,
-6L), class = c("tbl_df", "tbl", "data.frame"))
My plots codes are:
ggplot(df, aes(colour=SDTM_LabN)) +
geom_line(aes(x=ADY,y=result))
ggplot(df2, aes(colour=AEDECOD)) +
geom_segment(aes(x=AESTDY, xend=AEENDY, y=AEDECOD, yend=AEDECOD),) +
xlab("Duration")
How can I get sth that looks like this:
Upvotes: 0
Views: 650
Reputation: 41260
You should first make sure to calculate common xmin-xmax to both series.
Then with patwhwork
a suggested in comments or cowplot
:
xmin <- min(df$ADY ,df2$AESTDY)
xmax <- max(df$ADY ,df2$AESTDY)
p1 <- ggplot(df, aes(colour=SDTM_LabN)) +
geom_line(aes(x=ADY,y=result)) +
coord_cartesian(xlim = c(xmin,xmax))
p2 <- ggplot(df2, aes(colour=AEDECOD)) +
geom_segment(aes(x=AESTDY, xend=AEENDY, y=AEDECOD, yend=AEDECOD),) +
xlab("Duration") +
coord_cartesian(xlim = c(xmin,xmax))
library(cowplot)
plot_grid(plotlist = list(p1,p2),align='v',ncol=1)
Upvotes: 2