rename_geom_aes: Remap existing aesthetic mapping in the geom of a layer

Description Usage Arguments Examples

Description

Remap existing aesthetic mapping in the geom of a layer

Usage

1
rename_geom_aes(layer, new_aes, mapping = NULL)

Arguments

layer

The layer on which to work

new_aes

Named character vector listing how the plot aesthetics relate to the geom aesthetics

mapping

Optional aesthetic mapping from plot aesthetics to geom aesthetics

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
library(ggplot2)
library(dplyr)

# make a layer with its own fill scale
df1 <- data.frame(x = c(1, 2, 3))

ggplot(df1, aes(x = x)) +
  geom_tile(aes(fill = x, y = 2)) +
  geom_tile(aes(fill2 = x, y = 1)) %>% rename_geom_aes(new_aes = c("fill" = "fill2")) +
  scale_colour_viridis_c(aesthetics = "fill", guide = "legend", name = "viridis A", option = "A") +
  scale_colour_viridis_c(aesthetics = "fill2", guide = "legend", name = "viridis D")

# second example of layers with their own scales
scale_distiller <- function(aesthetics, palette, name, ...) {
  scale_colour_distiller(
    aesthetics = aesthetics,
    palette = palette,
    name = name, ...,
    guide = guide_legend(order = palette))
}

ggplot(mapping = aes(Sepal.Length, Sepal.Width)) +
  (geom_point(data = filter(iris, Species == "setosa"), aes(colour1 = Sepal.Width)) %>%
     rename_geom_aes(new_aes = c("colour" = "colour1"))) +
  (geom_point(data = filter(iris, Species == "versicolor"), aes(colour2 = Sepal.Width)) %>%
     rename_geom_aes(new_aes = c("colour" = "colour2"))) +
  (geom_point(data = filter(iris, Species == "virginica"), aes(colour3 = Sepal.Width)) %>%
     rename_geom_aes(new_aes = c("colour" = "colour3"))) +
  facet_wrap(~Species) +
  scale_distiller("colour1", 5, "setosa") +
  scale_distiller("colour2", 6, "versicolor") +
  scale_distiller("colour3", 7, "virginica") +
  theme_bw() +
  theme(legend.position = "bottom", legend.key.width = grid::unit(6, "pt"))

# multiple scales within a single layer
ggplot(iris, aes(Sepal.Length, Sepal.Width)) +
  geom_point(aes(col1 = Sepal.Width, col2 = Sepal.Width, col3 = Sepal.Width, group = Species)) %>%
    rename_geom_aes(
      new_aes = c("colour" = "col1", "colour" = "col2", "colour" = "col3"),
      aes(colour = case_when(group == 1 ~ col1, group == 2 ~ col2, TRUE ~ col3))
    ) +
    facet_wrap(~Species) +
    scale_distiller("col1", 5, "setosa") +
    scale_distiller("col2", 6, "versicolor") +
    scale_distiller("col3", 7, "virginica") +
    theme_bw() + theme(legend.position = "bottom", legend.key.width = grid::unit(6, "pt"))

# swap aesthetics in a geom
ggplot(iris, aes(Sepal.Length, fill = Species)) +
  geom_density(colour = "gray70", size = 3, alpha = 0.7) %>%
  rename_geom_aes(new_aes = c("fill" = "colour", "colour" = "fill"))

clauswilke/relayer documentation built on May 31, 2019, 10:46 p.m.