I have a problem when doing an animated pie chart with gganimate
and ggplot
.
I want to have normal pies each year, but my output is totally different.
You can see an example of the code using mtcars
:
library(ggplot2)
library(gganimate)
#Some Data
df<-aggregate(mtcars$mpg, list(mtcars$cyl,mtcars$carb), sum)
colnames(df)<-c("X","Y","Z")
bp<- ggplot(df, aes(x="", y=Z, fill=X, frame=Y))+
geom_bar(width = 1, stat = "identity") + coord_polar("y", start=0)
gganimate(pie, "output.gif")
An this is the output:
It works well when the frame
has only one level:
The ggplot code creates a single stacked bar chart with a section for every row in
df
. Withcoord_polar
this becomes a single pie chart with a wedge for each row in the data frame. Then when you usegg_animate
, each frame includes only the wedges that correspond to a given level ofY
. That's why you're getting only a section of the full pie chart each time.If instead you want a full pie for each level of
Y
, then one option would be to create a separate pie chart for each level ofY
and then combine those pies into a GIF. Here's an example with some fake data that (I hope) is similar to your real data:The pies in the GIF above are all the same size. But you can also change the size of the pies based on the sum of
count
for each level ofYear
(code adapted from this SO answer):If I can editorialize for a moment, although animation is cool (but pie charts are uncool, so maybe animating a bunch of pie charts just adds insult to injury), the data will probably be easier to comprehend with a plain old static line plot. For example:
Or maybe this: