Created
July 6, 2023 02:28
-
-
Save tetlabo/96cb2b816587298ff49e2be958538014 to your computer and use it in GitHub Desktop.
Rでfivethirtyeightのカラーパレット
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# fivethirty eight color palette | |
# タナカケンタ (鶴見教育工学研究所) | |
# ggthemesパッケージで提供されているパレットが3色しかないため、Pythonのmatplotlibのstyle sheetから借用して6色に | |
# パレットの作り方は以下を参考にした | |
# https://meghan.rbind.io/blog/2022-10-11-creating-custom-color-palettes-with-ggplot2/ | |
fivethirtyeight_color <- function(...) { | |
fivethirtyeight_colors <- c( | |
`blue` = "#008fd5", | |
`red` = "#fc4f30", | |
`yellow` = "#e5ae38", | |
`green` = "#6d904f", | |
`gray` = "#8b8b8b", | |
`purple` = "#810f7c") | |
cols <- c(...) | |
if (is.null(cols)) | |
return (fivethirtyeight_colors) | |
fivethirtyeight_colors[cols] | |
} | |
fivethirtyeight_palette <- function(palette = "main", ...) { | |
fivethirtyeight_palettes <- list( | |
`main` = fivethirtyeight_color("blue", "red", "yellow", "green", "gray", "purple"), | |
`highlight` = fivethirtyeight_color("red", "gray") | |
) | |
fivethirtyeight_palettes[[palette]] | |
} | |
palette_gen <- function(palette = "main", direction = 1) { | |
function(n) { | |
if (n > length(fivethirtyeight_palette(palette))) | |
warning("Not enough colors in this palette!") | |
else { | |
all_colors <- fivethirtyeight_palette(palette) | |
all_colors <- unname(unlist(all_colors)) | |
all_colors <- if (direction >= 0) all_colors else rev(all_colors) | |
color_list <- all_colors[1:n] | |
} | |
} | |
} | |
palette_gen_c <- function(palette = "main", direction = 1, ...) { | |
pal <- fivethirtyeight_palette(palette) | |
pal <- if (direction >= 0) pal else rev(pal) | |
colorRampPalette(pal, ...) | |
} | |
scale_fill_fivethirtyeight <- function(palette = "main", direction = 1, ...) { | |
ggplot2::discrete_scale( | |
"fill", "fivethirtyeight", | |
palette_gen(palette, direction), | |
... | |
) | |
} | |
scale_colour_fivethirtyeight <- function(palette = "main", direction = 1, ...) { | |
ggplot2::discrete_scale( | |
"colour", "fivethirtyeight", | |
palette_gen(palette, direction), | |
... | |
) | |
} | |
scale_color_fivethirtyeight <- scale_colour_fivethirtyeight | |
scale_color_fivethirtyeight_c <- function(palette = "main", direction = 1, ...) { | |
pal <- palette_gen_c(palette = palette, direction = direction) | |
scale_colour_gradient2(low = fivethirtyeight_palette("main")[1], mid = fivethirtyeight_palette("main")[3], high = fivethirtyeight_palette("main")[2], ...) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment