I'll use the mtcars dataset as an example. I'd like to transition between one variable (cyl) and another variable (hp) for the same data points based on fill color. However, the scale is set for the entire range between 4:335. Thus, when cyl is shown all the points look the same because their color is "squashed", for lack of a better term, by the upper bound of hp. What I'd like to have happen is that the color scale while cyl is being filled is 4:8 and when hp is being shown is 52:335. Here's a minimal example
library(ggplot2)
library(gganimate)
library(RColorBrewer)
library(grDevices)
myPalette <- colorRampPalette(rev(brewer.pal(11, "Spectral")))
anim <- ggplot(mtcars, aes(mpg, disp)) +
geom_point(shape = 21, colour = "black", size = 3, stroke = 0.5, show.legend = T, aes(fill = cyl)) +
geom_point(shape = 21, colour = "black", size = 3, stroke = 0.5, show.legend = T, aes(fill = hp)) +
scale_fill_gradientn(colours = myPalette(100))+
transition_layers(layer_length = 1, transition_length = 2) +
enter_fade() + enter_grow()
anim
One option is to use fill for one variable, and colour for the other, using the fact that some point shapes use fill and the others colour. I'm not 100% happy with the result, it may need some tweaking to get the point sizes to match up:
anim <- ggplot(mtcars, aes(mpg, disp)) +
geom_point(shape = 16, size = 3, show.legend = T, aes(colour = cyl)) +
geom_point(shape = 21, size = 3, stroke = 0, show.legend = T, aes(fill = hp)) +
scale_fill_gradientn(colours = myPalette(100))+
scale_colour_gradientn(colours = myPalette(100))+
transition_layers(layer_length = 1, transition_length = 2) +
enter_fade() + enter_grow()