Reputation: 43
I'm new to gganimate
and was having difficulty figuring out how to do this.
I'd like to show the spread in two different levels of a variable by animating colour transitions. I want to show this by having the narrow level
transition through a smaller range of colours than the wider level
in the same amount of time. Is this possible?
Here's the reproducible example I have up-to now.
library(ggplot2)
df <- data.frame(x = rep(c("narrow", "wide"), each = 1000),
y = c(sort(runif(n = 1000, min = 6, max = 7)),
sort(runif(n = 1000, min = 3, 10))),
animate.time = c(1:1000))
ggplot(data = df, aes(x = x, fill = y)) +
geom_bar()
Created on 2021-06-12 by the reprex package (v2.0.0)
As part of this, the color scale that each bar uses should be the same, but the narrow
x should occupy a narrower range of the color range than the wide
x.
I used geom_bar
because I don't want the shape of the visualisation to change, however I'm not sure how to proceed. I tried adding animate.time
so that gganimate
would have something to step through, but then I don't see how I'm supposed to make it change colors based on y
.
I'd appreciate any pointers.
Upvotes: 0
Views: 548
Reputation: 43
There is an easier way to do this based on this.
library(colorspace)
library(gganimate)
library(ggplot2)
# Narrow Visualization
narrow<-data.frame(x = rep(10,10),
state_cont=rep(1:2, each = 5))
ggplot(data = narrow, aes(x = x, fill = state_cont)) +
geom_bar() +
colorspace::scale_fill_continuous_sequential(palette = "Reds 3", begin = 0.4, end = .6) +
transition_states(states = state_cont) + theme_void() +
theme(legend.position = "none")
# Wide Visualization
wide <- data.frame(x=rep(10,10),
state_cont=rep(1:2, each = 5))
ggplot(data = wide, aes(x = x, fill = state_cont)) +
geom_bar() +
colorspace::scale_fill_continuous_sequential(palette = "Reds 3", begin = 0, end = 1) +
transition_states(states = state_cont) + theme_void() + theme(legend.position = "none")
The explanation is that for this particular question, you don't want to set every single value that it should oscillate through, it'd be much easier to simply set the boundaries in the scale_fill_continuous_sequential()
via the begin
and end
arguments. Then, gganimate
will automatically cycle through based on state_cont
Upvotes: 2