I have some ggplot objects animated via gganimate, and I would like to change the speed of the animation.
Here is a reproducible example from the github repo here: https://github.com/dgrtwo/gganimate
library(gapminder)
library(ggplot2)
theme_set(theme_bw())
p <- ggplot(gapminder, aes(gdpPercap, lifeExp, size = pop, color = continent, frame = year)) +
geom_point() +
scale_x_log10()
library(gganimate)
gganimate(p)
This animation takes about 12 seconds to cycle all the way through. How could I make it cycle through in say 6 seconds?
I have tried setting time to different values, but to no avail, and it is not clear from the help page.
gganimate(p, time = 0.1)
Update
The interval seems to generally work, but still unclear to me how I could make this work within an Rmarkdown report. As an example, if I place the code below in a file called test.R and then run rmarkdown::render('test.R') my animation runs at the default speed instead of the expected increased speed. How would I make this work in the context of rmarkdown::render? I've been trying various things from looking here: https://github.com/dgrtwo/gganimate/commit/3aa2064cdfff30feb2b00724ad757fd5a5a62621, but to no avail.
knitr::opts_chunk$set(message = FALSE, warning = FALSE, fig.show = 'animate')
library(gapminder)
library(ggplot2)
theme_set(theme_bw())
p <- ggplot(gapminder, aes(gdpPercap, lifeExp, size = pop, color = continent, frame = year)) +
geom_point() +
scale_x_log10()
library(gganimate)
capture.output(gganimate(p, interval = 0.2))
We need to set interval option:
gganimate(p, interval = 0.2)
From animation package manual, see ani.options:
interval a positive number to set the time interval of the animation (unit in seconds); default to be 1.
Related
Hi I'm trying to save high quality (300 dpi) images using RStudio but no luck so far. I've looked around a lot on the internet but no answer seems to work. Even when I run the code below, no file shows up on my computer. Any help is appreciated!
install.packages("gapminder")
library(gapminder)
data("gapminder")
attach(gapminder)
plot(lifeExp ~ log(gdpPercap))
ggsave("filename.png",dpi = 300)
It works fine if you use ggplot() from ggplot2 instead of plot()
Packages and data
library(ggplot2)
library(gapminder)
data("gapminder")
attach(gapminder)
Solution
ggplot(gapminder,
aes(x = log(gdpPercap), y = lifeExp)) +
geom_point()
ggsave("filename.png",dpi = 300)
Here are some tweaks you came make to make it more similar to plot() appearance:
ggplot(gapminder,
aes(x = log(gdpPercap), y = lifeExp)) +
geom_point(shape = 1) +
theme_linedraw()
output from last code
From a database called "datoschile" that incorporates 6 variables, I have created a panel data called "magrupados3" that uses the variable "Periodo" as an identity variable and I have filtered thstrong texte information using only "Importaciones" and "Exportaciones" variables
This the excel file needed to work with this code
https://gitlab.com/pedritoandrade/how-can-i-make-a-transition-to-a-linear-model
datos <- read.xlsx("C:\\Users\\PEDRO ANDRADE 2019\\Desktop\\Curso Betametrica\\Analisis exploratorio y automatizacion de reportes\\datoschile.xlsx",
sheet = "Hoja1",
detectDates = T)`
magrupados3 <- melt(datos, id.vars = "Periodo")%>%
filter(variable == "Exportaciones" | variable == "Importaciones")`
Then with this data, I have created a graph using geom_line and geom_point and also the tendency line using geom_smooth. This is the code and the result you can see it here:
magrupados4 <- ggplot(data=magrupados3,aes(x=Periodo,y=value))+
geom_line()+geom_point()+facet_wrap(variable~.,scales = "free",ncol = 2)+
geom_smooth(method = "lm",formula= y~x,col="black",se=F)`
Graph
I want to make a transition of this graph. In other words, I want that geom_line and the regression line (geom_smooth) to appear simultaneously each year(my variable that represents year in my data is called "Periodo").
Can someone help me with this?
It seems that you need to use the R package gganimate in combination with the R packages: devtools, ggplot2, gifski, and av.
Check this link: https://gganimate.com/
Here is an example that I took from that website. It is working in my computer. You need the libraries that are in my example. Some libraries were not in the website example. Be careful with that. In your code, you did not use the last two lines of this example (transition_time(year) + ease_aes('linear')). Also, I guess that you did not install all the R libraries that are needed.
# install.packages('devtools')
# devtools::install_github('thomasp85/gganimate')
library(devtools)
library(gapminder)
library(ggplot2)
library(gganimate)
library(gifski)
library(av)
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) + labs(title = 'Year: {frame_time}', x = 'GDP per capita', y = 'life expectancy')+
transition_time(year) +
ease_aes('linear')
I've been trying to gain some experience with ggplot2 using Kieran Healy's excellent online book as a starting point, but I've run into a quirk I can't figure out. Using Gapminder data, I'm trying to create a scatterplot showing life expectancy vs GDP per capita. I'd like to include two years of data, distinguishing the years using both color and shape. Finally, I would like to label an outlier, Kuwait in 1952.
I know I could use annotate to do this manually, but I was hoping someone might have a more elegant solution. In addition, I'd love to know why this code, which seems perfectly legitimate to this novice, is not working the way it seems it should. Thanks very much!
library(ggplot2)
library(gapminder)
gap <- subset(gapminder,year==min(year) | year==max(year))
gap$year <- as.character(gap$year)
p <- ggplot(data = gap,
mapping = aes(y = lifeExp,
x = gdpPercap,
col = year))
p + geom_point(aes(shape=year)) + theme_classic() +
scale_x_log10(labels=scales::dollar) +
geom_text_repel(data=subset(gap,gdpPercap>100000),
mapping=aes(label=country)) +
labs(title="Life expectancy by output per capita",
y="",x="GDP per capita")
I personally prefer using annotate for annotation, because you won't have exactly this type of surprises that you have with using a geom. Also, geoms tend to draw for each row of your data frame, so this may create some ugly effects on the fonts/ shapes.
library(ggplot2)
library(ggrepel)
library(gapminder)
gap <- subset(gapminder,year==min(year) | year==max(year))
gap$year <- as.character(gap$year)
ggplot(data = gap, aes(y = lifeExp, x = gdpPercap, col = year)) +
geom_point(aes(shape=year)) +
theme_classic() +
scale_x_log10(labels=scales::dollar) +
annotate(geom = "label_repel",
x = gap$gdpPercap[gap$gdpPercap>100000],
y = gap$lifeExp[gap$gdpPercap>100000],
label = gap$country[gap$gdpPercap>100000])
Created on 2020-04-25 by the reprex package (v0.3.0)
I'm having an issue when exporting stat_density2d plots.
ggplot(faithful, aes(eruptions, y = waiting, alpha = ..density..)) +
stat_density2d(geom = 'tile', contour = F)
When exporting as a png it looks like so:
But when I export as a PDF a grid appears:
I'm assuming that this is because the boundaries of the tiles overlap and so have equivalent of a doubled alpha value.
How can I edit just the edges of the tiles to stop this from happening?
Secondary question:
As Tjebo mentioned geom = 'raster' would fix this problem. However, this raises a new issue that only one group gets plot.
df <- faithful
df$new <- as.factor(ifelse(df$eruptions>3.5, 1, 0))
ggplot(df, aes(eruptions, waiting, fill = new, alpha = ..density..)) +
stat_density2d(geom = 'tile', contour = F) +
scale_fill_manual(values = c('1' = 'blue', '0' = 'red'))
ggplot(df, aes(eruptions, waiting, fill = new, alpha = ..density..)) +
stat_density2d(geom = 'raster', contour = F) +
scale_fill_manual(values = c('1' = 'blue', '0' = 'red'))
help on this second issue would also be much appreciated!
Now I decided to transform my comment into an answer instead. Hopefully it solves your problem.
There is an old, related google thread on this topic - It seems related to how the plots are vectorized in each pdf viewer.
A hack is suggested in this thread, but one solution might simply be to use geom = 'raster' instead.
library(ggplot2)
ggplot(faithful, aes(eruptions, y = waiting, alpha = ..density..)) +
stat_density2d(geom = 'raster', contour = F)
Created on 2019-08-02 by the reprex package (v0.3.0)
If you have a look at the geom_raster documentation - geom_raster is recommended if you want to export to pdf!
The most common use for rectangles is to draw a surface. You always want to use geom_raster here because it's so much faster, and produces smaller output when saving to PDF
edit - second part of the question
Your tile plot can't be correct - you are creating cut-offs (your x value), so the fill should not overlap. This points to the core of the problem - the alpha=..density.. probably calculates the density based on the entire sample, and not by group. I think the only way to go is to pre-calculate the density (e.g., using density(). In your example, for demonstration purpose, we have this luckily precalculated, as faithfuld (this is likely not showing the results which you really want, as it is the density on the entire sample!!).
I'd furthermore recommend not to use numbers as your factor values - this is pretty confusing for you and R. Use characters instead. Also, ideally don't use df for a sample data frame, as this is a base R function;)
Hope this helps
mydf <- faithfuld ## that is crucial!!! faithfuld contains a precalculated density column which is needed for the plot!!
mydf$new <- as.factor(ifelse(mydf$eruptions>3.5, 'large', 'small'))
ggplot(mydf, aes(eruptions, waiting)) +
geom_raster(aes(fill = new, alpha = density), interpolate = FALSE)
Created on 2019-08-02 by the reprex package (v0.3.0)
In the latest version of gganimate by https://github.com/thomasp85 I would like to choose which parts of the plot I can keep static throughout the animation and which will be animated. In the previous version of gganimate you could specify the frame in the aes of ggplot. Thus you could create a base plot that would be static and plot the animated plot over this. How can similar be achieved in the latest version?
This has already been addressed in an issue for gganimate on GitHub: https://github.com/thomasp85/gganimate/issues/94
Basically you specify the the layers that are meant to be static with a separate data frame from the one you initially passed to ggplot. The example in the GitHub ticket I referred to is
library(gganimate)
#> Loading required package: ggplot2
ggplot(dat = data.frame(x=1:10,y=1:10), aes(x=x,y=y)) +
geom_point() +
geom_line(data = data.frame(x2 = 1:10, y = 1:10),
aes(x = x2, y = y, group = 1)) +
transition_time(x)
animate(last_plot(), nframes = 50)
Here the line is held static, while the point is moving.