Skip to content

Instantly share code, notes, and snippets.

@z3tt
Created October 16, 2025 08:50
Show Gist options
  • Save z3tt/6fc1fc64214d1e17cc5c291ce1792a52 to your computer and use it in GitHub Desktop.
Save z3tt/6fc1fc64214d1e17cc5c291ce1792a52 to your computer and use it in GitHub Desktop.
Recolor images using any palette
library(ggplot2)
library(patchwork)
# get photo
img <- magick::image_read("https://www.yan-holtz.com/img/team/YH_pic_square.png")
# retrieve lightness
c <- magick::image_channel(img)
img_df <- tibble::as_tibble(as.data.frame.table(drop(as.integer(c[[1]]))))
img_df <- dplyr::mutate(img_df, across(c(Var1, Var2), as.numeric))
# base plot
r <-
ggplot(img_df) +
geom_raster(aes(x = Var2, y = Var1, fill = Freq)) +
scale_y_reverse() +
coord_fixed(expand = FALSE) +
guides(fill = guide_colorbar(reverse = TRUE)) +
theme_void(base_size = 12) +
theme(
legend.position = "top",
legend.key.height = unit(.5, "lines"),
legend.key.width = unit(2.2, "lines"),
legend.title = element_blank(),
legend.text = element_blank(),
legend.ticks = element_blank(),
legend.justification = "left",
legend.box.margin = margin(3, 0, 0, 0),
plot.margin = margin(rep(7, 4))
)
# define breaks for nice legend
s <- seq(0, 255, length.out = 100)
## ggplot blues ---------------------------------------------------------------
r + scale_fill_gradient(breaks = s)
## viridis --------------------------------------------------------------------
r + scale_fill_viridis_c(breaks = s)
## colorbrewer ----------------------------------------------------------------
r + scale_fill_distiller(palette = "YlOrBr", breaks = s)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment