Skip to content

Instantly share code, notes, and snippets.

@Selbosh
Last active November 6, 2019 17:25
Show Gist options
  • Save Selbosh/b2f7d0139343c5bb357a8140bfb58a45 to your computer and use it in GitHub Desktop.
Save Selbosh/b2f7d0139343c5bb357a8140bfb58a45 to your computer and use it in GitHub Desktop.
Seen a plot that uses a rainbow colour palette? Convert it to a less contemptuous colour scheme with this script.
#############################
# Fix a rainbow-coloured plot
#############################
rainbow2viridis <- function(img) {
# Input: `img`, an H x W x 3 array of RGB values from an image file
dimnames(img) <- list(height = NULL, width = NULL,
rgb = c('r', 'g', 'b'))
data <- reshape2::melt(img)
data <- reshape2::dcast(data, width + height ~ rgb)
data <- subset(data, !(r == 1 & g == 1 & b == 1)) # omit white pixels
data <- cbind(data, t(rgb2hsv(t(data[, c('r', 'g', 'b')]),
maxColorValue = 1)))
data <- within(data, black <- r == 0 & g == 0 & b == 0)
# Visualize with proper colour palette.
print(
ggplot(data) + aes(width, height) +
geom_tile(fill = 'black', data = subset(data, black)) +
geom_tile(aes(fill = h), data = subset(data, !black)) +
scale_fill_viridis_c() +
scale_y_reverse() +
coord_fixed() +
theme_void() +
theme(legend.position = 'none')
)
# Return the data for future use.
invisible(data)
}
#############################
# Generate a hideous example
#############################
png('example.png', 1000, 1000)
filled.contour(volcano, color.palette = rainbow)
dev.off()
example <- png::readPNG('example.png')
#############################
# Fix it.
#############################
library(ggplot2)
png('fixed.png', 1000, 1000)
data <- rainbow2viridis(example)
dev.off()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment