Skip to content

Instantly share code, notes, and snippets.

@eliocamp
Created January 24, 2018 19:30
Show Gist options
  • Save eliocamp/bbbb066c19edd712311b0a1129a6ad33 to your computer and use it in GitHub Desktop.
Save eliocamp/bbbb066c19edd712311b0a1129a6ad33 to your computer and use it in GitHub Desktop.
Use circular colorscale in R
library(ggplot2)
df <- data.frame(x = rnorm(100), y = rnorm(100))
df$dir <- with(df, atan2(y, x))
df$t <- 1:nrow(df)
## The default is, of course, ridiculous.
(g <- ggplot(df, aes(dir, t)) +
geom_point(aes(color = dir)) +
coord_polar())
## First approach. It doesn't work.
g + scale_color_gradient2(low = "blue", high = "blue", mid = "red")
library(colorspace)
angle <- seq(0, 2*pi, length.out = 20)
A <- 100*sin(angle)
B <- 100*cos(angle)
## Two different ways. Which is better?
plot(circular2 <- polarLAB(70, 60, angle*180/pi))
plot(circular <- LAB(60, A, B))
g + scale_color_gradientn(colours = hex(circular, fixup = TRUE))
g + scale_color_gradientn(colours = hex(circular2, fixup = TRUE))
@eliocamp
Copy link
Author

library(ggplot2)

df <- data.frame(x = rnorm(100), y = rnorm(100))

df$dir <- with(df, atan2(y, x))
df$t <- 1:nrow(df)

## The default is, of course, ridiculous. 
(g <- ggplot(df, aes(dir, t)) + 
        geom_point(aes(color = dir)) +
        coord_polar())

## First approach. It doesn't work.
g + scale_color_gradient2(low = "blue", high = "blue", mid = "red")

library(colorspace)

angle <- seq(0, 2*pi, length.out = 20)
A <- 100*sin(angle)
B <- 100*cos(angle)

## Two different ways. Which is better?
plot(circular2 <- polarLAB(70, 60, angle*180/pi))

plot(circular <- LAB(60, A, B))

g + scale_color_gradientn(colours = hex(circular, fixup = TRUE))

g + scale_color_gradientn(colours = hex(circular2, fixup = TRUE))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment