Skip to content

Instantly share code, notes, and snippets.

@timcdlucas
Last active February 8, 2018 10:21
Show Gist options
  • Save timcdlucas/b255cc1da7e557d72c0cc10129effbfc to your computer and use it in GitHub Desktop.
Save timcdlucas/b255cc1da7e557d72c0cc10129effbfc to your computer and use it in GitHub Desktop.
hsv two way colour ramp
#load packages
require(raster)
require(colorplaner)
require(ggplot2)
#here's some dummy data
r1<- raster(ncol=10, nrow=10)
set.seed(0)
values(r1) <- runif(ncell(r1))
r2<- raster(ncol=10, nrow=10)
values(r2) <- runif(ncell(r2))
#here I create a grid with which I can extract information on the raster datasets
grid<-raster(ncol=10, nrow=10)
grid[] <- 1:ncell(grid)
grid.pdf<-as(grid, "SpatialPixelsDataFrame")
grid.pdf$r1<-(extract(r1,grid.pdf))
grid.pdf$r2<-(extract(r2,grid.pdf))
#here I convert the grid to a dataframe for plotting in ggplot2
grid.df<-as.data.frame(grid.pdf)
ggplot(data=grid.df,aes(x,y,fill=r1,fill2=r2))+geom_raster()+scale_fill_colourplane("")
# hsv
# Position along diagonal is value
# Distance from the diagonal is saturation
# upper triangle or lower triangle is hue.
col_func <- function(x, y, hue1 = 0.3, hue2 = 0.8, light_grey = 0, dark_grey = 1){
x[x == 0] <- 0.000001
y[y == 0] <- 0.000001
x[x == 1] <- 0.999999
y[y == 1] <- 0.999999
# upper or lower triangle?
u <- y > x
hue <- ifelse(u, hue1, hue2)
# distace from (0,0) to (x,y)
hyp <- sqrt(x^2 + y^2)
# Angle between x axis and line to our point
theta <- asin(y / hyp)
# Angle between 45 degree line and (x,y)
phi <- ifelse(u, theta - pi/4, pi/4 - theta)
phi <- ifelse(phi < 0, 0, phi)
# Distance from 45 degree line and (x,y)
s <- hyp * sin(phi) / sqrt(2)
# Draw line from (x, y) to 45 degree line that is at right angles.
# How far along 45 degree line, does that line join.
v <- (hyp * cos(phi) / sqrt(2))
scaled_v <- v * (dark_grey - light_grey) + light_grey
# Get hsv values.
sapply(seq_along(x), function(i) hsv(hue[i], s[i], scaled_v[i]))
}
ggplot(data=grid.df,aes(x,y,fill=r1,fill2=r2))+
geom_raster()+
scale_fill_colourplane(name = "",
na.color = "white",
color_projection = col_func,
limits_y = c(0,1),limits=c(0,1),
hue1 = 0.5, hue2 = 0.1,
dark_grey = 0.8,
light_grey = 0.2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment