eliocamp / ggnewscale

Multiple Fill, Color and Other Scales in `ggplot2`
https://eliocamp.github.io/ggnewscale/
GNU General Public License v3.0
406 stars 18 forks source link

`guides` properties before `new_scale` are not preserved #39

Closed danlooo closed 2 years ago

danlooo commented 2 years ago

Hello,

thanks for developing such a useful package! It seems that ggnewscale::scale_new_color overwrites parameters of ggplot2::guides, when they were written before the creation of the new scale. I was able to fix this by using color_new instead of color in function guides after the creation of the new scale. Is this intended behavior? For me, it is a little confusing that former parameters are not preserved.

library(ggnewscale)
library(tidyverse)

packageVersion("ggnewscale")
#> [1] '0.4.5'

data <-
  iris %>%
  head(10) %>%
  mutate(
    color_a = factor(Petal.Length),
    color_b = factor(Petal.Width)
  )

data %>%
  ggplot(aes(Sepal.Length, Sepal.Width)) +
  geom_point(aes(color = color_a)) +
  guides(color = guide_legend(ncol = 2, nrow = 2))

data %>%
  ggplot(aes(Sepal.Length, Sepal.Width)) +
  geom_point(aes(color = color_b)) +
  guides(color = guide_legend(ncol = 1, nrow = 4))

# first color guide gets overwritten
data %>%
  ggplot(aes(Sepal.Length, Sepal.Width)) +
  geom_point(aes(color = color_a)) +
  guides(color = guide_legend(ncol = 2, nrow = 2)) +
  new_scale_color() +
  geom_point(aes(color = color_b)) +
  guides(color = guide_legend(ncol = 1, nrow = 4))

# workarround: do guides after creating a new scale
data %>%
  ggplot(aes(Sepal.Length, Sepal.Width)) +
  geom_point(aes(color = color_a)) +
  new_scale_color() +
  geom_point(aes(color = color_b)) +
  guides(color = guide_legend(ncol = 1, nrow = 4)) +
  guides(color_new = guide_legend(ncol = 2, nrow = 2))

Created on 2022-02-15 by the reprex package (v2.0.0)

eliocamp commented 2 years ago

Thanks for the issue. This is fixed now on the development version of the package (devtools::install_github("eliocamp/ggnewscale@dev").

library(ggplot2)
library(ggnewscale)

packageVersion("ggnewscale")
#> [1] '0.4.5.9000'

ggplot(head(iris, 10), aes(Sepal.Length, Sepal.Width)) +
  geom_point(aes(color = factor(Petal.Length))) +
  guides(color = guide_legend(ncol = 2, nrow = 2)) +
  new_scale_colour() +
  geom_point(aes(color = factor(Petal.Width))) +
  guides(color = guide_legend(ncol = 1, nrow = 4))

As a workaround in the current CRAN version you can define guides inside scales to get the expected behaviour.

ggplot(head(iris, 10), aes(Sepal.Length, Sepal.Width)) +
  geom_point(aes(color = factor(Petal.Length))) +
  scale_color_discrete(guide = guide_legend(ncol = 2, nrow = 2)) +
  new_scale_colour() +
  geom_point(aes(color = factor(Petal.Width))) +
  scale_color_discrete(guide = guide_legend(ncol = 1, nrow = 4))

Created on 2022-02-15 by the reprex package (v2.0.1)

eliocamp commented 2 years ago

The update is now on CRAN.