Home > Software engineering >  ggplot2 - create one colorbar legend for two plots with different data-range
ggplot2 - create one colorbar legend for two plots with different data-range

Time:02-17

I have the following gridded 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 ?

CodePudding user response:

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)
  • Related