I have a dataset that looks like this:
d <- data.frame(w = runif(3000),
x = runif(3000),
y = rnorm(3000),
z = rep(LETTERS[1:3], 1000))
I can plot w
as a continuous variable with some colour palette; scale_colour_viridis_c()
does this nicely:
library(ggplot2)
ggplot(d, aes(x, y))
geom_point(aes(colour = w))
scale_colour_viridis_c()
But say I want to express w
in terms of z
too. I can't with the option
argument in scale_colour_viridis_c()
because "EXPR must be a length 1 vector".
How can I do this such that there are more than one colour palette used (i.e., unique(d$z)
)?
CodePudding user response:
One option to have multiple color (or ...) scales for the same aesthetic would be the ggnewscale
package which TBMK requires to split your data by z
and use multiple layers. To make this a bit easier I use purrr::imap
to create the layers for each z
:
set.seed(123)
library(ggplot2)
library(ggnewscale)
d_split <- split(d, d$z)
limits <- range(d$w)
ggplot(mapping = aes(x, y))
purrr::imap(d_split, function(x, y) {
list(
geom_point(aes(colour = w), data = x),
scale_colour_viridis_c(option = y, limits = limits),
new_scale_colour()
)
})
CodePudding user response:
Modifying your sample data slightly so that the plot is at least vaguely sensible:
library(tidyverse)
library(ggplot2)
d <- data.frame(w = round(runif(99), 1),
x = runif(99),
y = round(rnorm(99), 1),
z = rep(LETTERS[1:3], 33))
ggplot(d, aes(x, y))
geom_point(aes(colour = interaction(w, z)))
interaction()
creates a discrete categorisation so you can't use scale_colour_viridis_c()
.