Reputation: 2283
I am trying to create a plot where I show two measures for the same set of points, one with a discrete scale and one with a continuous scale. I want to show the plots side-by-side, and getting them into facets would be great. Unfortunately, I can't figure out how to have one color scale in one facet and a different color scale in another.
library(tidyverse)
disc <- tibble(x = rnorm(100), y = rnorm(100), color = sample(1:3, 100, replace = TRUE), model = "discrete")
cont <- tibble(x = rnorm(100), y = rnorm(100), color = rnorm(100, 10), model = "continuous")
# want this to be discrete
ggplot(disc, aes(x = x, y = y, color = factor(color))) +
geom_point() + scale_color_discrete()
# want this to be continuous
ggplot(cont, aes(x = x, y = y, color = color)) +
geom_point() + scale_color_viridis_c()
# This would be prettier!
bind_rows( disc, cont ) %>%
ggplot(aes(x = x, y = y, color = color)) +
geom_point() +
facet_wrap(~model)
Created on 2021-10-16 by the reprex package (v2.0.0)
I realize that this is probably outside the intended use of facet. But I'm having a harder time getting the maps to print side-by-side in a coherent way and thought this could be a more sustainable shortcut.
Upvotes: 0
Views: 701
Reputation: 2283
Just learned about ggnewscale
in my searching, and it seems to be easy enough! :
library(tidyverse)
library(ggnewscale)
disc <- tibble(x = rnorm(100), y = rnorm(100), color = sample(letters[1:3], 100, replace = TRUE), model = "discrete")
cont <- tibble(x = rnorm(100), y = rnorm(100), color = rnorm(100, 10), model = "continuous")
ggplot(mapping = aes(x = x, y = y)) +
geom_point(data = disc, aes(color = color)) +
scale_color_discrete("discrete") +
new_scale_color() +
geom_point(data = cont, aes(color = color)) +
scale_color_viridis_c("continuous") +
facet_wrap(~model)
Created on 2021-10-16 by the reprex package (v2.0.0)
Upvotes: 2