I would like to display animations made by the package gganimate side by side or at least in the same document.
Plots to work with:
library(ggplot2)
library(gganimate)
anime_one <-
ggplot(mtcars, aes(factor(cyl), mpg)) +
geom_boxplot() +
# Here comes the gganimate code
transition_states(
gear,
transition_length = 2,
state_length = 1
) +
enter_fade() +
exit_shrink() +
ease_aes('sine-in-out')
anime_two <-
ggplot(mtcars, aes(factor(cyl), mpg, fill = factor(cyl))) +
geom_boxplot() +
# Here comes the gganimate code
transition_states(
gear,
transition_length = 2,
state_length = 1
) +
enter_fade() +
exit_shrink() +
ease_aes('sine-in-out')
First attempt:
library(patchwork)
anime_one + anime_two
Error in UseMethod("ggplot_gtable") :
no applicable method for 'ggplot_gtable' applied to an object of class
"gganim_built"
Second attempt:
library(patchwork)
animate(anime_one+anime_two)
This actually renders and doesn't give an error, but the result is an animation of only the last "gganim_built" object (here anime_two)
Third attempt (Works, but not really what I am looking for)
The only halfway solution I have found is to include everything in a Rmarkdown document, and then make codecunks with animation calls (only one animation call pr codechunk otherwise it doesn't work), and finally knit the document to HTML:
```{r}
animate(anime_one)
```
```{r}
animate(anime_two)
```
Has anyone managed to make gganimate objects appear side by side?
Thanks in advance.
Seems that gganimate help docs are being rewritten and maybe you can find a solution about "animation composition" here:
https://github.com/thomasp85/gganimate/wiki/Animation-Composition
Under the title "Placing Animations side-by-side with magick" there's a method to do such thing.
Hope this help
Related
I have created some awesome graphs that I want to export to my Word document. Yea, should write in Markdown but... you know... someday!
However, how do I resize the graphs to the right dimensions while labels stay "within" the perimeter? See the following examples (code is at the end of the document).
I want to insert the following graph into my word document:
Looks great! Not when I insert it into the document:
Labels are two tiny, and I would love to stretch it vertically, so the width is greater than the height. So I managed to produce this:
And this is were I am stuck. How do I keep the labels within the perimeters? And is there a better way to "fit" the word document than guessing correct dimensions?
Thanks!
This is the code:
library(ggplot2)
df <- mpg # Load sample data
# First test graph
ggplot(data = df, mapping = aes(cyl, hwy)) +
geom_smooth() +
geom_point() +
geom_point() +
labs(y = "This is just one very long label to prove a point ..... 1234",
x = "Cyl") +
theme_classic() +
theme(legend.title = element_blank())
ggsave("test1.png")
# Modified test graph to add fit the Word document
ggplot(data = df, mapping = aes(cyl, hwy)) +
geom_smooth() +
geom_point() +
geom_point() +
labs(y = "This is just one very long label to prove a point ..... 1234",
x = "Cyl") +
theme_classic(base_size = 12) + # SIZE CHANGED
theme(legend.title = element_blank())
ggsave("test2.png", width = 8, height = 4) # DIMENSIONS DEFINED
A solution I tend to use involves the officer package as mentioned above. This used to be able export graphs as vector objects to docx so you could change sizes and text in the graph when it's in the document. This seems to have been suspended in recent versions, but still works for powerpoint. The following code puts the graph as a grouped shape in a powerpoint slide where you can tweak it before copying into word:
library(ggplot2)
library(officer)
library(tidyverse)
df <- mpg # Load sample data
# First test graph
plot2 <- ggplot(data = df, mapping = aes(cyl, hwy)) +
geom_smooth() +
geom_point() +
geom_point() +
labs(y = "This is just one very long label to prove a point ..... 1234",
x = "Cyl") +
theme_classic(base_size = 12) + # SIZE CHANGED
theme(legend.title = element_blank())
pptx <- read_pptx()
pptx %>%
add_slide() %>%
# This first line puts it in as a static png image for comparison
ph_with(plot2, location = ph_location_type(type = "body")) %>%
add_slide() %>%
# This line puts in a shape object, which can be ungrouped and edited
ph_with(rvg::dml(ggobj = plot2),
width = 8,
height = 4,
location = ph_location_type(type = "body"))
#> pptx document with 2 slide(s)
print(pptx, "test_graph.pptx")
Created on 2020-12-08 by the reprex package (v0.3.0)
That's a sort of tweaky solution which at least allows you visual control over sizes. This used to be more easily provided through the export package (available on GitHub), but it's not on CRAN anymore and behind the scenes used the now defunct parts of officer to put vector graphics in docx documents.
Edit: See this issue on GitHub for an explanation of why vector graphics to docx is no longer an option through officer.
Goal
To control the animation using start/stop/pause buttons.
Problem
The animation package can save the created animation as a HTML page using the saveHTML() function (example here). But it requires "expr = an R expression to be evaluated to create a sequence of images" as the first argument.
However, gganimate creates a gganim object, and I can't seem to find a function that can save the animation as a HTML page with buttons. The available anim_save() function does not save as HTML. Is there a workaround to do that?
Example code for animation
If you have any ideas please share. For your reference, I'm putting below the gganimate code from its website.
library(ggplot2)
library(gganimate)
ggplot(mtcars, aes(factor(cyl), mpg)) +
geom_boxplot() +
# Here comes the gganimate code
transition_states(
gear,
transition_length = 2,
state_length = 1
) +
enter_fade() +
exit_shrink() +
ease_aes('sine-in-out')
The following worked for me in RStudio, though I didn't see "current" listed as an option for device in gganimate::animate:
library(gganimate)
library(animation)
# name the above gganimate example as p
p <- ggplot(mtcars, aes(factor(cyl), mpg)) +
geom_boxplot() +
transition_states(
gear,
transition_length = 2,
state_length = 1
) +
enter_fade() +
exit_shrink() +
ease_aes('sine-in-out')
# pass the animate command to saveHTML
saveHTML(animate(p,
nframes = 10, # fewer frames for simplification
device = "current"),
img.name = "gganimate_plot",
htmlfile = "gg.html")
I got a html file with animation control buttons & an image folder with 10 png files.
I'm trying to learn about animating plots with gganimate, and I'm wondering if someone has a tip for the problems I'm running into. In an effort to make things simple, I'm doing this by creating a new project in RStudio Cloud, installing the ggplot2, gganimate, and datasauRus packages, and following this example from Isaac Faber:
library(datasauRus)
library(ggplot2)
library(gganimate)
ggplot(datasaurus_dozen, aes(x=x,y=y)) +
geom_point() +
theme_minimal() +
transition_states(dataset,3,1) +
ease_aes()
This creates a series of .PNG files but I cannot see an animation. Some seem to suggest that I can see it using the "print" function, but this does not work either.
I have also been unable to export this as a .GIF, although I have followed the advice given here. Specifically, the magick packages does not work for me (I get the same error about my images not being magick image objects), and when I try the following code:
p <- ggplot(datasaurus_dozen, aes(x=x,y=y)) +
geom_point() +
theme_minimal() +
transition_states(dataset,3,1) +
ease_aes()
anim <- animate(p)
anim_save("myfilename.gif",anim)
R tells me that The
animation object does not specify a save_animation method.
I've been unable to find examples or documentation that tells me how to specify a save_animation method. If anyone has advice on this topic, it would be greatly appreciated!
you're doing one step too many:
library(datasauRus)
library(ggplot2)
library(gganimate)
p <- ggplot(datasaurus_dozen, aes(x=x,y=y)) +
geom_point() +
theme_minimal() +
transition_states(dataset,3,1) +
ease_aes()
anim_save("myfilename.gif",p)
I solved this by specifying the gifski_renderer() in animate():
library(tidyverse)
library(gganimate)
library(gapminder)
g <- ggplot(gapminder, aes(gdpPercap, lifeExp, size = pop, colour = country)) +
geom_point(alpha = 0.7, show.legend = FALSE) +
scale_colour_manual(values = country_colors) +
scale_size(range = c(2, 12)) +
scale_x_log10() +
facet_wrap(~continent) +
# Here comes the gganimate specific bits
labs(title = 'Year: {frame_time}', x = 'GDP per capita', y = 'life expectancy') +
transition_time(year) +
ease_aes('linear')
animate(g, height=400, width=600, renderer=gifski_renderer())
anim_save("gapminder.gif", g)
Note: this is the default renderer for animate(), but somehow needed to be specified explicitly. After doing it the first time, I no longer need to set it, a behavior I can't explain.
I'd like to create a markdown document out of my R script. I managed it to display different barplots, piecharts, a leaflet map and so on.
But it doesn't work with ggplot.
{r, eval=TRUE, echo=TRUE, warning=FALSE, message=FALSE}
p <- qplot() +
theme_classic() +
ggtitle("Title") +
coord_fixed(ratio = 1) +
xlab("wrong") +
ylab("super") +
geom_polygon(data=fortify(data1),
aes(x=long, y=lat, group=group), alpha=0.1, fill=NA, col="black", size=0.1) +
geom_point(data = as.data.frame(data2),
aes(x = coords.x1, y = coords.x2, color = pal1), shape=4, alpha=1)
p + theme(legend.position="right")
The plot looks totally fine if i export it with ggsave, but in the markdown the x axis is pressed together.
Without a reproducible example, it is difficult to work out your problems. However, you could try to change a few lines (each at a time) to see if it makes a difference. Particularly, I would remove the line coord_fixed(ratio = 1) + to see what happens. You could also try different ratio numbers as well to get what you want.
If this does not fix your problem, please provide a reproducible example data.
I'll often set a theme early on in a script, with a specific base font size.
# CODE BLOCK 1
library(tidyverse)
ggplot(mtcars, aes(cyl, mpg)) +
geom_col() +
theme_set(theme_bw(base_size = 20))
Then I'll want to switch the theme and the font size for a different plot later on in my script. I will try to accomplish this with code like below.
# CODE BLOCK 2
ggplot(mtcars, aes(factor(cyl))) +
geom_bar() +
theme_set(theme_gray(base_size = 6))
I just ran these two code blocks on a fresh R session and when I ran code block 2 the theme and base font size did not change to the arguments listed above. I immediately ran code block 2 again and the theme and font size changed to the arguments shown above. Why is theme_set() only working intermittently?
My session info follows:
OS: Windows 7 64 bit
R: 3.4.4
R Studio: 1.1.442
ggplot2: 2.2.1.9000
Please try this. See also here ?theme_set
theme_set(theme_bw(base_size = 20))
ggplot(mtcars, aes(cyl, mpg)) +
geom_col()
theme_set(theme_gray(base_size = 6))
ggplot(mtcars, aes(factor(cyl))) +
geom_bar()
Or simply without the theme_setfunction
ggplot(mtcars, aes(factor(cyl))) +
geom_bar() +
theme_gray(base_size = 6)