LKremer/ggpointdensity

common legend for multiple figures

SONG-MAN opened this issue · 3 comments

Thank you very much for providing such useful codes. I plotted several figures, but the legend of each picture is different.
I want to combine multiple figures with only one legend used.
I am wondering if I could change the "adjust" parameter of each figure to make them have the same legends.
Or there are other ways to solve this.

Thank you for your attention.

Hi @SONG-MAN,
thanks for the question.

I can think of two solutions to your problem: Either you use faceting, or you manually set the legend limits.
I will give you a quick example:

library(ggplot2)
library(dplyr)
library(viridis)
library(ggpointdensity)

df1 <- tibble(x = rnorm(7000, sd = 1),
              y = rnorm(7000, sd = 10),
              group = "foo")

df2 <- tibble(x = rnorm(3000, mean = 1, sd = .5),
              y = rnorm(3000, mean = 7, sd = 5),
              group = "bar")

If I just plot df1 and df2 separately, they will have different legends of course. To fix it, the easiest solution is to merge df1 and df2 into one data frame (or tibble) and then use facet_wrap() or facet_grid():

all_data <- bind_rows(df1, df2)

ggplot(data = all_data, mapping = aes(x = x, y = y)) +
  geom_pointdensity() +
  scale_color_viridis() +
  facet_wrap(~group)

image
This way, you will have a separate plot panel for each of the two sub-data sets, but they will share one legend. Of course, your merged data frame needs a grouping column, so that you can still distinguish the two data sets.

Another option is to produce two separate plots where you manually set the limits of the color scale, like this:

ggplot(data = df1, mapping = aes(x = x, y = y)) +
  geom_pointdensity() +
  scale_color_viridis(limits = c(NA, 420))

image

ggplot(data = df2, mapping = aes(x = x, y = y)) +
  geom_pointdensity() +
  scale_color_viridis(limits = c(NA, 420))

image

I hope this answers your question!

Thank you very much for providing the solution and the example. It works great!

Nice!