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.
Related
I am trying to plot a line and a dot using ggplot2. I looked at but it assumes the same dataset is used. What I tried to do is
library(ggplot2)
df = data.frame(Credible=c(0.2, 0.3),
len=c(0, 0))
zero=data.frame(x0=0,y0=0)
ggplot(data=df, aes(x=Credible, y=len, group=1)) +
geom_line(color="red")+
geom_point()+
labs(x = "Credible", y = "")
ggplot(data=zero, aes(x=x0, y=y0, group=1)) +
geom_point(color="green")+
labs(x = "Credible", y = "")
but it generates just the second plot (the dot).
Thank you
Given the careful and reproducible way you created your question I am not just referring to the old answer as it may be harder to transfer the subsetting etc.
You initialize a new ggplot object whenever you run ggplot(...).
If you want to add a layer on top of an existing plot you have to operate on the same object, something like this:
ggplot(data=df, aes(x=Credible, y=len, group=1)) +
geom_line(color="red")+
geom_point()+
labs(x = "Credible", y = "") +
geom_point(data=zero, color="green", aes(x=x0, y=y0, group=1))
Note how in the second geom_point the data source and aesthetics are explicitly specified instead to prevent them being inherited from the initial object.
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'm a newbie, so this might be super basic.
When I run this code
Dplot <- qplot(x = diamonds$carat, y = diamonds$price, color = diamonds$color) +
ggtitle("An A+ plot") +
xlab("carat") +
ylab("price") +
geom_point()
Dplot <- Dplot + facet_wrap(vars(diamonds$clarity))
Dplot
I get an error message that says:
Error in gList(list(x = 0.5, y = 0.5, width = 1, height = 1, just =
"centre", :
only 'grobs' allowed in "gList"
I've tried googling, but haven't been able to figure out what the issue is.
I would advise against using qplot except in the most basic cases. It teaches bad habits (like using $) that should be avoided in ggplot.
We can make the switch by passing the data frame diamonds to ggplot(), and putting the mappings inside aes() with just column names, not diamonds$. Then the facet_wrap works fine as long as we also omit the diamonds$:
Dplot = ggplot(diamonds, aes(x = carat, y = price, color = color)) +
ggtitle("An A+ plot") +
xlab("carat") +
ylab("price") +
geom_point()
Dplot + facet_wrap(vars(clarity))
Dplot + facet_wrap(~ clarity) # another option
Notice the code is actually shorter because we don't need to type diamonds$ all the time!
The vars(clarity) option works fine, more traditionally you would see formula interface used ~ clarity. The vars() option is new-ish, and will play a little nicer if you are writing a function where the name of a column to facet by is stored in a variable.
I'm running in a bit of a problem plotting some data with ggplot2: I want to use a facet_wrap over a variable AdultInputProp, but R doesn't find the variable and instead returns an Error in as.quoted(facets) : object 'AdultInputProp' not found. Now I understand that this simply means that R can't find this variable in the dataset used to plot, but if I ask ggplot2 to instead use the same variable for to create a shape scale, it works just fine. Any idea what the problem might be?
Sorry, I'm not too sure how to make a minimal working example with a generated df from scratch, so here's the df I'm using, and the code bellow. I've also tried using facet_grid instead of facet_wrap but ran into the same problem.
The code here with facets returns the above-mentioned error:
df.plot.GBPperAIP <- ggplot(df.sum.GBPperAIP,
aes(x=TestIteration, y=Error,
colour=GoalBabblingProp,
group=interaction(GoalBabblingProp,
AdultInputProp))) +
facet_wrap(AdultInputProp) +
xlab("Step") + ylab("Mean error") + theme_bw(base_size=18) +
scale_colour_discrete(name = "Goal babbling proportion") +
geom_line(position = position_dodge(1000)) +
geom_errorbar(aes(ymin=Error-ci,
ymax=Error+ci),
color="black", width=1000,
position = position_dodge(1000)) +
geom_point(position = position_dodge(1000),
size=1.5, fill="white")
This other code, exactly the same except for the facet_wrap line deleted and with shape added works fine:
df.plot.GBPperAIP <- ggplot(df.sum.GBPperAIP,
aes(x=TestIteration, y=Error,
colour=GoalBabblingProp,
shape=AdultInputProp,
group=interaction(GoalBabblingProp,
AdultInputProp))) +
xlab("Step") + ylab("Mean error") + theme_bw(base_size=18) +
scale_colour_discrete(name = "Goal babbling proportion") +
geom_line(position = position_dodge(1000)) +
geom_errorbar(aes(ymin=Error-ci,
ymax=Error+ci),
color="black", width=1000,
position = position_dodge(1000)) +
geom_point(position = position_dodge(1000),
size=1.5, fill="white")
facet_wrap expects a formula, not just a naked variable name. So you should change it to
...
facet_wrap(~ AdultInputProp) +
...
I'm trying to remove the title of a legend in ggplot2:
df <- data.frame(
g = rep(letters[1:2], 5),
x = rnorm(10),
y = rnorm(10)
)
library(ggplot2)
ggplot(df, aes(x, y, colour=g)) +
geom_line(stat="identity") +
theme(legend.position="bottom")
I've seen this question and none of the solutions there seem to work for me. Most give an error about how opts is deprecated and to use theme instead. I've also tried various versions of theme(legend.title=NULL), theme(legend.title=""), theme(legend.title=element_blank), etc. Typical error messages are:
'opts' is deprecated. Use 'theme' instead. (Deprecated; last used in version 0.9.1)
'theme_blank' is deprecated. Use 'element_blank' instead. (Deprecated; last used in version 0.9.1)
I'm using ggplot2 for the first time since version 0.9.3 was released and I'm finding it difficult to navigate some of the changes...
You were almost there : just add theme(legend.title=element_blank())
ggplot(df, aes(x, y, colour=g)) +
geom_line(stat="identity") +
theme(legend.position="bottom") +
theme(legend.title=element_blank())
This page on Cookbook for R gives plenty of details on how to customize legends.
This works too and also demonstrates how to change the legend title:
ggplot(df, aes(x, y, colour=g)) +
geom_line(stat="identity") +
theme(legend.position="bottom") +
scale_color_discrete(name="")
Another option using labs and setting colour to NULL.
ggplot(df, aes(x, y, colour = g)) +
geom_line(stat = "identity") +
theme(legend.position = "bottom") +
labs(colour = NULL)
Since you may have more than one legends in a plot, a way to selectively remove just one of the titles without leaving an empty space is to set the name argument of the scale_ function to NULL, i.e.
scale_fill_discrete(name = NULL)
(kudos to #pascal for a comment on another thread)
For Error: 'opts' is deprecated. Use theme() instead. (Defunct; last used in version 0.9.1)'
I replaced opts(title = "Boxplot - Candidate's Tweet Scores") with
labs(title = "Boxplot - Candidate's Tweet Scores"). It worked!