ggplot2 – create one colorbar legend for two plots with different data-range

Issue

I have the following gridded dataset from where I create two different dataframes:

df_1=read.csv("example.csv")

df_2=df_1
df_2$var=df_2$var+50

Then I plot them with ggplot2 and metR:

library(ggplot2)
library(metR)

plot_df_1=ggplot()+
  geom_contour_fill(data=df_1, aes(x=lon, y=lat, z=var), alpha=0.9) +
  scale_fill_steps(name = "", low = "#bdd7e7", high = "#08519c",
                   breaks = seq(0, 160, by = 10)) 

print(plot_df_1)

enter image description here

plot_df_2=ggplot()+
  geom_contour_fill(data=df_2, aes(x=lon, y=lat, z=var), alpha=0.9) +
  scale_fill_steps(name = "", low = "#bdd7e7", high = "#08519c",
                   breaks = seq(0, 160, by = 10)) 

print(plot_df_2)

enter image description here

Is there a way I can create one unique colorbar legend so that I can better compare the two plots?

The legend should have same colors and associated values for each plot.

In the two plots above the higest (lowest) values in both plots have the same color, but they differ in terms of magnitude. For example is it possible to show darker colors for plot_df_2 ?

Solution

This is one way of implementing the solution described in @Mamoun Benghezai’s comment:

library(tidyverse)
library(metR)

# Combine df1 and df2 to a single df ("df_table")
df_table <- map_df(.x = list("df_1" = df_1,
                             "df_2" = df_2),
                   .f = bind_rows,
                   .id = "src")

# Plot the combined dataset
plot_df_1 <- ggplot(df_table) +
  geom_contour_fill(aes(x=lon, y=lat, z=var), alpha=0.9) +
  scale_fill_steps(name = "", low = "#bdd7e7", high = "#08519c",
                   breaks = seq(0, 160, by = 10)) +
  facet_wrap(~src)

print(plot_df_1)

Answered By – jared_mamrot

Answer Checked By – Senaida (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.