This is a test version of Biostars. For the public version, visit https://www.biostars.org.
combine two density plots in one plot

Hello,

I plotted a density plot for 2 time points for 3 genes. I want to combine both time points in one plot.

I am not sure how to do it? any suggestion would be helpful.

Here is the code I used for plotting:

dp_9_a = ggplot(mr_d_9_rsv, aes(x=abs(LFC), fill=id)) +
  geom_density(alpha=.3) +
  geom_vline(xintercept = 0, color="red", lwd=1, linetype="dashed")+
  facet_grid(. ~ id) +
  ylim(c(0,1.5)) +
  xlim(c(-2,9))+
  theme_bw()+ 
  theme(plot.title = element_text(hjust = 0.5,size=12), legend.position = "none")



dp_24_a = ggplot(mr_d_24_rsv, aes(x=abs(LFC), fill=id)) +
  geom_density(alpha=.3) +
  geom_vline(xintercept = 0, color="red",lwd=1, linetype="dashed")+
  facet_grid(. ~ id) +
  theme_bw() +
  ylim(c(0,1.5)) +
  xlim(c(-2,9))+
  theme(plot.title = element_text(hjust = 0.5,size=12), legend.position = "none")

enter image description here

Thanks in advance

r ggplot2 density_plot

1 answer

Use patchwork library to do so

 library(patchwork)

 combined_plot <- dp_9_a / dp_24_a

 combined_plot

Or

library(ggplot2)
library(dplyr)


mr_d_9_rsv$time_point <- '9'
mr_d_24_rsv$time_point <- '24'
combined_data <- bind_rows(mr_d_9_rsv, mr_d_24_rsv)
combined_plot <- ggplot(combined_data, aes(x=abs(LFC), fill=id)) +
  geom_density(alpha=.3) +
  geom_vline(xintercept = 0, color="red", lwd=1, linetype="dashed") +
  facet_grid(time_point ~ id) +
  ylim(c(0,1.5)) +
  xlim(c(-2,9)) +
  theme_bw() + 
  theme(plot.title = element_text(hjust = 0.5, size=12), legend.position = "none")
combined_plot

You can also use cowplot or other R packages to perform the same.

Log in to answer this question.