--- title: "scale_* functions (ggplot2)" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{scale_* functions (ggplot2)} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>", fig.width = 5 ) library(paletteNMR) suppressPackageStartupMessages({ library(dplyr) library(lubridate) library(ggplot2) library(scales) library(patchwork) library(datasets) }) theme_set(theme_nmr() + theme(panel.grid.major.y = element_line(colour = "grey50"))) ``` In addition to the NMR palettes themselves, `paletteNMR` contains `scale_*` functions for use in ggplot2 graphics Below, two figures with discrete color scales are created using `scale_nmr_color_*` variants and `scale_nmr_fill` variants respectively: ```{r iris} iris |> ggplot(aes(Sepal.Length, Petal.Length)) + geom_point(aes(colour = Species), size = rel(4), alpha = 1/1.2) + scale_nmr_color_categorical(pal = "quad", set = "C", reverse = TRUE) iris |> ggplot(aes(Sepal.Length, Petal.Length)) + geom_point(aes(fill = Species), shape = 21, size = rel(4), alpha = 1/1.2) + scale_nmr_fill_categorical(pal = "quad", set = "C", reverse = TRUE) ``` Testing cases with more discrete colors (using the `airmiles` dataset from the `datasets` pkg) ```{r miles} airmiles |> as.data.frame() |> setNames("miles") |> mutate(yr = time(airmiles) |> parse_date_time("Y")) |> mutate(yr_grp = floor_date(yr, "10 years") |> year() |> factor()) |> ggplot(aes(yr, miles)) + geom_point(aes(color = yr_grp), size = rel(4), alpha = 1/1.2) + labs(x = NULL, y = "Miles traveled", color = NULL) + scale_x_datetime(date_breaks = "10 years", date_labels = "%Y") + scale_y_continuous(labels = unit_format(unit = "k", scale = 1e-3)) + scale_nmr_color_categorical(pal = "quad", set = "C", reverse = TRUE) ``` Continuous values work too! ```{r iris_cont} iris |> ggplot(aes(Sepal.Length, Petal.Length)) + geom_point(aes(colour = Petal.Length), size = rel(4), alpha = 1/1.2) + scale_nmr_color_sequential(set = "GT6", discrete = FALSE, reverse = TRUE) + guides(color = "none") iris |> ggplot(aes(Sepal.Length, Petal.Length)) + geom_point(aes(fill = Petal.Length), shape = 21, size = rel(4), alpha = 1/1.2) + scale_nmr_fill_sequential(set = "GT6", discrete = FALSE, reverse = TRUE) + guides(fill = "none") ``` Take care to specify the right arguments. For example, using `scale_nmr_color_sequential` assumes a divergent palette (i.e. `pal = "diverg"`), so it only requires specifying the `set` argument (e.g. `set = "GT6"`) ```{r iris_error, error=TRUE} iris |> ggplot(aes(Sepal.Length, Petal.Length)) + geom_point(aes(colour = Petal.Length), size = rel(4), alpha = 1/1.2) + scale_nmr_color_sequential(pal = "GT6", discrete = FALSE, reverse = TRUE) + guides(color = "none") ```