Making a custom scale_color_gradient but assigning number values to the colors

165 Views Asked by At

I'm having trouble getting a custom color gradient to work. I want to assign certain colors to certain values but have the colors flow. This is what I've got so far.

thi_color_scale<-scale_color_gradientn(
  colors = c("#660000", "#cc0000", "#e69f00", "#9a9a9a"),
  values = c(0, 2.9, #critically low
             3, 5, #low
             5, 8, #int
             8, max(data$avg_total_egg_thi)))#high

iso_egg_plot_thi_conc<- ggplot(data = data, aes(x = d13c_lc, y = d15n, shape = egg_thi_status, color = avg_total_egg_thi)) +
  geom_point(size = 1.75, stroke = 1) +
  
  # Use the custom color gradient scale
  thi_color_scale
iso_egg_plot_thi_conc

plot enter image description here

I've tried finding the middle value of each of these ranges for the colors and just setting those as the number assigned to the color but that just spits out a grey plot.

1

There are 1 best solutions below

0
Mark On BEST ANSWER

The documentation for scale_color_gradientn says:

values

if colours should not be evenly positioned along the gradient this vector gives the position (between 0 and 1) for each colour in the colours vector. See rescale() for a convenience function to map an arbitrary range to between 0 and 1.

mtcars %>%
  ggplot(aes(x = mpg, y = wt, color = qsec)) +
  geom_point(size = 15) +
  scale_color_gradientn(colors = c("#660000", "#cc0000", "#e69f00", "#9a9a9a"), 
                        values = scales::rescale(c(0, 2.9, 3, 5, 8, max(mtcars$qsec)))) # duplicates can be removed by us, because they will be removed by ggplot later anyway

plot