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

I would like to change the color gradient to match a set of predefined thresholds / points and colors. 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")

      

+3


source to share


2 answers


You can 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

+3


source


Use cut

and match cells to colors. My code assumes -0.103200 is the minimum of your vector (for sorting the number of boxes).



trh <- c(-0.103200, 0.007022, 0.094090, 0.548600, Inf)
colors <- c("#EDF8E9", "#BAE4B3", "#74C476", "#238B45")

x <- runif(30, min = -0.103200, max = 1)
xc <- cut(x, breaks = trh)
colors[xc]

      

+3


source







All Articles