首页 > 解决方案 > creating 2 separate ggplots with same color scale

问题描述

library(raster)
library(ggplot2)
library(dplyr)
library(colorspace)
#I hope these are all the required packages, if not please let me know.

r1 <- raster(system.file("external/test.grd", package="raster"))
r2 <- r1^1.1
as.data.frame(r1, xy=TRUE) %>%drop_na() %>% 
  ggplot(aes(x=x, y=y)) +
  geom_raster(aes(fill = test)) +
  scale_fill_gradientn(
    colours = hcl.colors(10, "YlGnBu"),trans = "reverse",
    breaks =c(505, 1100, 1600))

as.data.frame(r2, xy=TRUE) %>%drop_na() %>% 
ggplot(aes(x=x, y=y)) +
  geom_raster(aes(fill = test)) +
  scale_fill_gradientn(
    colours = hcl.colors(10, "YlGnBu"),trans = "reverse",
    breaks =c(505, 1100, 1600))

I have this example data. How can I make the 2 plots have the same colors for the same values & have the same defined breaks? The break numbers were just chosen arbitrarily. I want to have the plots separate.

I have found this link which tackles the exact problem but my data is different and I can't make it work. (it doesn't matter if some numbers are out of range)

what i tried so far:

rng = range(c((1900), (200)))

as.data.frame(r, xy=TRUE) %>%drop_na() %>%
 ggplot(aes(x=x, y=y)) + geom_raster(aes(fill = test)) + 
 scale_fill_gradientn(colours = hcl.colors(10, "YlGnBu"),trans = "reverse", 
                      midpoint=mean(rng), breaks =seq(505, 1100, 1600),
                      limits=c(floor(rng[1]), ceiling(rng[2])))

Can anyone help me please with this problem?

标签: rggplot2

解决方案


The problem is that you have reversed the fill scale with trans = "reverse", so the limits also need to be inverted:

as.data.frame(r1, xy=TRUE) %>%drop_na() %>% 
  ggplot(aes(x=x, y=y)) +
  geom_raster(aes(fill = test)) +
  scale_fill_gradientn(
    colours = hcl.colors(10, "YlGnBu"),trans = "reverse",
    breaks =c(505, 1100, 1600), limits = c(2000, 0))

enter image description here

as.data.frame(r2, xy=TRUE) %>%drop_na() %>% 
ggplot(aes(x=x, y=y)) +
  geom_raster(aes(fill = test)) +
  scale_fill_gradientn(
    colours = hcl.colors(10, "YlGnBu"),trans = "reverse",
    breaks =c(505, 1100, 1600), limits = c(2000, 0))

enter image description here


推荐阅读