Why is ggsave not saving my plot to my computer? - r

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

Related

Annotating figure changes legend in ggplot2

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)

Animating with ggplot and gganimate

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.

replicate plot() using ggplot()

Please see attached plots using the standard plot() function vs ggplot() function.
I am currently playing around with theme() to try and replicate the plot() background/panels and general look etc. but I can't get it quite right.
I've tried:
theme_update(panel.background = element_rect(fill = "white", colour = "grey50"))
But it's not quite what I'm looking for and it reverts back to the gray background whenever I relaunch RStudio....
Any helpful pointers would be greatly appreciated.
Thanks
Following my comment I provide a reproducible example using diamonds dataset:
library(ggplot2)
library(ggthemes)
set.seed(100)
mydata <- diamonds[sample(nrow(diamonds), 100), ]
ggplot(data = mydata, aes(x = carat, y = price)) +
geom_point(shape = 1) +
theme_base()

Change speed of R ggplot gganimate when using rmarkdown render

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.

crosstalk and plotly - ggplotly does not accept shareddata-object

I've been trying to generate interactive linked visualizations with by use of the plotly and crosstalk libraries. As shown in the example below, it seems to be possible to pass ggplot2 a 'shared Dataframe'-Object in order to generate linked views with ggplotly(). When i try to run this example i get the following error-message:
Error: ggplot2 doesn't know how to deal with data of class SharedData/R6
I'm using the current versions of ggplot2 (v. 2.2.1) and plotly (4.5.6). What can cause this error?
Thx for help!
The example which i'm trying to replicate can be found here:
https://cpsievert.github.io/plotly_book/linking-animated-views.html
library(gapminder)
library(crosstalk)
library(ggplot2)
library(plotly)
g <- crosstalk::SharedData$new(gapminder, ~continent)
gg <- ggplot(g, aes(gdpPercap, lifeExp, color = continent, frame = year)) +
geom_point(aes(size = pop, ids = country)) +
geom_smooth(se = FALSE, method = "lm") +
scale_x_log10()
ggplotly(gg) %>%
highlight("plotly_hover")
Error: ggplot2 doesn't know how to deal with data of class SharedData/R6

Resources