rggplot2visualizationbioinformatics

Is there a way to make two scatter density plots share the same legend in R


I am using geom_pointdensity() to draw scatter density plot in R. Is there a way to draw them side by side as subplots and also share the same legend with the same range?


Solution

  • In the future, please use a minimal, reproducible example so that we can help you more easily.

    Nevertheless, here is an example using the facet_wrap function.

    library(tidyverse)
    library(ggpointdensity)
    library(viridis)
    
    # Example dataset
    dat <- bind_rows(
      tibble(x = rnorm(7000, sd = 1),
             y = rnorm(7000, sd = 10),
             group = "foo"),
      tibble(x = rnorm(3000, mean = 1, sd = .5),
             y = rnorm(3000, mean = 7, sd = 5),
             group = "bar"))
    
    # Plot figure using facet_wrap
    ggplot(data = dat, mapping = aes(x = x, y = y)) +
      geom_pointdensity() +
      scale_color_viridis() +
      theme_bw() +
      facet_wrap(~group)
    

    Created on 2024-07-05 with reprex v2.1.0