BKeys
BKeys

Reputation: 13

How to assign a maximum value shown on a colour ramp in R

This is probably a simple thing to do in R, but I want to set a maximum value shown on a predefined colour ramp. I've been asked to use cmocean colour palettes and have a numeric variable with values ranging from 0 to ~10. However, I want the darkest colour to apply to values => 5. For example, any value of 5 and above will be displayed as the same/ "maximum" colour available. I don't want to remove the data above 5 so subsetting isn't an option. I hope this makes sense, thank you!

Upvotes: 1

Views: 874

Answers (2)

StupidWolf
StupidWolf

Reputation: 46898

I guess something like this? You cut the values according to a defined breaks, and in your case, 5 to 10 is 1 break and you assign one color to it:

library(cmocean)
x = sort(runif(100,0,10))
pal = cmocean("balance")(11)
lbl = cut(x,breaks = c(seq(0,5,length.out=10),10),right=FALSE)
names(pal) = unique(lbl)

Plot it, using the code from this post for a colorbar:

layout(matrix(c(1,2),ncol=2),widths=c(5,1))

plot(values,rep(1,length(values)),col=pal[lbl],pch=20)

my.colors = pal
z=matrix(1:10,nrow=1)
y=seq(0,5,len=10)
image(1,y,z,col=pal,axes=FALSE,xlab="",ylab="")
axis(2)

enter image description here

Upvotes: 1

jared_mamrot
jared_mamrot

Reputation: 26515

There is at least one way to do this, see if this approach works for your use-case:

library(tidyverse)
library(palmerpenguins)
#install.packages("cmocean")
library(cmocean)
library(cowplot)
library(ggbeeswarm)

plot_1 <- penguins %>% 
  na.omit() %>%
  ggplot(aes(x = species, y = flipper_length_mm, color = body_mass_g)) +
  geom_quasirandom()  +
  scale_color_cmocean(name = "deep")

plot_2 <- penguins %>% 
  na.omit() %>%
  ggplot(aes(x = species,
             y = flipper_length_mm,
             color = body_mass_g)) +
  geom_quasirandom()  +
  scale_color_cmocean(name = "deep",
                      limits = c(2500, 4000),
                      oob = scales::squish,
                      labels = c("2500", "3000", "3500", "4000+"))
cowplot::plot_grid(plot_1, plot_2, labels = "AUTO")

Explanation: Panel "A" (plot_1) doesn't have scale limits, Panel "B" (plot_2) has scale limits. The oob option ("Out Of Bounds) is also needed in addition to the scale limits in Panel "B" to 'keep' the darkest colour, otherwise the colours above 4000 are grey. I also altered the labels on the legend (labels option) to change "4000" to "4000+", but up to you whether you think that's useful or not.

example.png

Upvotes: 0

Related Questions