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

Legend issues when using `guides(...)` #49

Closed GreenGilad closed 1 year ago

GreenGilad commented 2 years ago

Hi,

I am trying to use ggnewscale to plot multiple sets of points each with their own color and alpha scales. I run the following code


  groups <- unique(fits[, group.by])
  if(is.null(cols)) {
    cols <- setNames(scales::hue_pal()(length(groups)), groups)
  }

  p <- ggplot(fits) + 
    facet_wrap(paste0("~",facet.by), scales=facet.scales, ncol = ncol) + 
    scale_x_continuous(expand = c(0,0)) + 
    theme_classic() + 
    theme(strip.background = element_blank(), strip.text = element_blank())

  for(g in groups) {
    p <- p + 
      geom_point(aes(x,y, color=X.weights., alpha=X.weights.), fits[fits[,group.by] == g,], inherit.aes = F) + 
      scale_color_gradientn(name = g, colors=colorRampPalette(c("white", cols[[g]]))(10)[-1]) + 
      scale_alpha(name = g, range=c(min.point.alpha,1)) + 
      labs(color=g, alpha=g)  +       
      new_scale("alpha") + 
      new_scale("color")
  }

and get the plot: image where as visible the point size and color are in different guides in the legend. By adding guides(color_new=guide_legend(g), alpha_new=guide_legend(g)) after the new_scale("color") in the loop I am able to get a warning:

In names(guides)[to_change] <- paste0(names(guides), "_new") :
  number of items to replace is not a multiple of replacement length

and the following plot: image

This is almost there but there is a problem: now the legned isn't aligning with the correct set of points. Looking a bit into the code it is probably because the new scales are named X_new and then next time X_new_new and X_new_new_new. Then the line of the guides won't work as hoped.

A possible fix is to change the function to: new_scale("alpha", "some.name") instead of only adding the _new (or leaving it as the default behavior) and then using that name in the guides will probably work

eliocamp commented 2 years ago

Currently there's a bug when using more than 2 scales (see #45 for a workaround). It's not an obvious fix and I haven't had the time to look deeper into it.

A possible fix is to change the function to: new_scale("alpha", "some.name") instead of only adding the _new (or leaving it as the default behavior) and then using that name in the guides will probably work

This is a fantastic idea. I'll implement it for the next release.

GreenGilad commented 2 years ago

Thanks for the quick reply!

I tried the workaround of returning to a previous version but it didn't seem to work (I think the issue is a bit different). Will wait for the next release :)

eliocamp commented 2 years ago

Huh, then it might be a different issue. I'll look into it.

eliocamp commented 1 year ago

This should be fixes on the latest dev, which is now on its way to CRAN.