Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a custom colour scale using ggplot2 and geom_tile?

Tags:

r

ggplot2

I would like to modify the colour gradient in order to match a set of predefined thresholds/cutpoints and colours. How can I do this?

Cutoff values: -0.103200, 0.007022, 0.094090, 0.548600 Colors: "#EDF8E9", "#BAE4B3", "#74C476", "#238B45"

    #Create sample data

        pp <- function (n,r=4) {
              x <- seq(-r*pi, r*pi, len=n)
              df <- expand.grid(x=x, y=x)
              df$r <- sqrt(df$x^2 + df$y^2)
              df$z <- cos(df$r^2)*exp(-df$r/6)
              df
            }

            pp(20)->data

#create the plot

library(ggplo2)
            p <- ggplot(pp(20), aes(x=x,y=y))
            p + geom_tile(aes(fill=z))

#Generate custom colour ramp

library(RColorBrewer)

cols <- brewer.pal(4, "Greens")
like image 719
Filipe Dias Avatar asked Mar 19 '23 08:03

Filipe Dias


1 Answers

You may try scale_fill_brewer. First, bin your z values:

df <- pp(20)
df$z_bin <- cut(df$z, breaks = c(-Inf, -0.103200, 0.007022, 0.094090, 0.548600))

Plot:

ggplot(data = df, aes(x = x, y = y, fill = z_bin)) +
  geom_tile() +
  scale_fill_brewer(palette = "Greens")

enter image description here

like image 105
Henrik Avatar answered Apr 05 '23 20:04

Henrik