Problem:
Hi, I try to make an animated plot in a rmarkdown document. Here is my code:
```{r lmSim, fig.show='animate'}
library(animation)
library(plyr)
oopt = ani.options(interval = 0.3, nmax = 101)
a <- sort(rnorm(100, 2))
b <- sort(rnorm(100, 7))
out <- vector("list", 101)
for (i in 1:ani.options("nmax")) {
ji <- seq(from = 0, to = 5, by = .05)
a <- jitter(a, factor = 1, amount = ji[i])
fab1 <- lm(a ~ b)
coe <- summary(fab1)$coefficients
r2 <- summary(fab1)$r.squared
if (coe[2, 4] < .0001) p <- " < .0001"
if (coe[2, 4] < .001 & coe[2, 4] > .0001) p <- " < .001"
if (coe[2, 4] > .01) p <- round(coe[2, 4], 3)
plot(a ~ b, main = "Linear model")
abline(fab1, col = "red", lw = 2)
text(x = min(b) + 2, y = max(a) - 1,
labels = paste("t = ", round(coe[2, 3], 3), ", p = ", p, ", R2 = ", round(r2, 3)))
out[[i]] <- c(coe[2, 3], coe[2, 4], r2)
ani.pause()
}
ani.options(oopt)
```
The loop work fine, and passed into a function, I'am able to save it in several formats with 'saveLatex', 'saveHTML' or 'saveVideo'. However, when 'knit' the .Rmd file in order to obtain a PDF, the animation does not appear, there is just this line written:
video of chunk lmSim
If I knit it in HTML, only the play button of the video is displayed. However, If I open the HTML in my browser (firefox) it is displayed correctly.
There is no error message displayed. I'm using R version 3.2.0, the latest R Studio version, 1.10.5 knitr version on a MacBook Pro Yosemite. I didn't find any relevant information or documentation to solve my problem.
Questions:
So, is it simply possible to have an embeded animation into a PDF generated with rmarkdown/knitr ?
Do I have to install another program to deal with videos in PDF (I have ffmpeg on my computer)?
Many thanks!
Thanks Yihui! It works very well with the following settings (reading the PDF with Adobe):
---
title: "Sim"
author: ""
header-includes:
- \usepackage{animate}
...
---
```{r lmSim, fig.show='animate', out.width = '6in'}
Have you tried with ggplot and gganimation? For example:
library(gapminder)
library(gganimate)
library(ggplot)
head(gapminder)
theme_set(theme_bw())
p <- ggplot(gapminder, aes(gdpPercap, lifeExp, size = 1, color = continent, frame = year)) +
geom_point() +
scale_x_log10()
animation<-gganimate(p, "your_animation.gif")#Or to your path
See that you need to save first your animation. You need to have establish your work directory.
After you can call it from the chat or html in markdown (not from the R chuck) like:
![your caption here](your_animation.gif)
May be it’s too late for this answer, but hopefully should help others. I recommend to save and run the R code as a separate file in the same directory and only import the animation as a gif to reduce lag in the presentation. This works for me in ioslides:
## Time series visualization
![time series](myanimation.gif){width=80%}
Related
I need to export a table I made in r from binding different values
enter image description here
I've tried with library(gridExtra) but it's not working (perhaphs I'm using it wrong)
FA=table(ant$municipionombre)
View(FA)
prop.table(table(ant$municipionombre))
#Percentage Relative Frequency/Frecuencia relativa porcentual
FR=FA/margin.table(FA)
View(FR)
#Cumulative Absolute Frequency/Frecuencia absoluta acumulada
FAA=cumsum(FA)
View(FAA)
#Cumulative Percentage Relative Frequency/Frecuencia relativa porcentual acumulada
FRP=cumsum(FA)/margin.table(FA)
View(FRP)
#Percentage by entry
perc=FR*100
perc
#Build a table with all variables (FA, FAA, FR, FRP, perc)
tab1=cbind(FA,FAA,FR,FRP,perc)
tab1
View(tab1)```
I don't really understand your code above, as you haven't provided useable sample data. But the fundamental question of how to export data to a PDF can be accomplished with the reporter package.
There are three steps:
Create the table content.
Create a report.
Write out the report.
Here is an example using the iris data frame.
library(reporter)
tbl <- create_table(iris) %>%
titles("My PDF Report")
rpt <- create_report("c:\\temp\\test.pdf", output_type = "PDF") %>%
add_content(tbl)
write_report(rpt)
Here is a portion of the PDF:
With using gridExtra package, you may consider following code below
maxrow = 35;
npages = ceiling(nrow(df)/maxrow)
pdf("test.pdf", height = 11, width = 8.5)
idx = seq(1, maxrow)
grid.table(df[idx,], rows = NULL)
for (i in 2:npages){
grid.newpage()
if(i * maxrow <= nrow(df)) {
idx = seq(1 + ((1 - 1) * maxrow), i*maxrow)
} else {
idx = seq(1 + ((i - 1) * naxriw), nrow(df))
}
grid.table(df[idx,], rows = NULL)
}
dev.off()
You may change height or width so I highly recommend try to make pdf with single page. Also df is table to write pdf.
I have 11 plots and used a looping function to plot them see my code below. However, I can't get them to fit in just 1 page or less. The plots are actually too big. I am using R software and writing my work in RMarkdown. I have spent almost an entire week trying to resolve this.
group_by(Firm_category) %>%
doo(
~ggboxplot(
data =., x = "Means.type", y = "means",
fill ="grey", palette = "npg", legend = "none",
ggtheme = theme_pubr()
),
result = "plots"
)
graph3
# Add statistical tests to each corresponding plot
Firm_category <- graph3$Firm_category
xx <- for(i in 1:length(Firm_category)){
graph3.i <- graph3$plots[[i]] +
labs(title = Firm_category[i]) +
stat_pvalue_manual(stat.test[i, ], label = "p.adj.signif")
print(graph3.i)
}
#output3.long data sample below as comments
#Firm_category billmonth Means.type means
#Agric 1 Before 38.4444
#Agric 1 After 51.9
Complete data is on my github: https://github.com/Fridahnyakundi/Descriptives-in-R/blob/master/Output3.csv
This code prints all the graphs but in like 4 pages. I want to group them into a grid. I have tried to add all these codes below just before my last curly bracket and none is working, please help me out.
library(cowplot)
print(plot_grid(plotlist = graph3.i[1:11], nrow = 4, ncol = 3))
library(ggpubr)
print(ggarrange(graph3.i[1:11], nrow = 4, ncol = 3))
I tried the gridExtra command as well (they all seem to do the same thing). I am the one with a mistake and I guess it has to do with my list. I read a lot of similar work here, some suggested
dev.new()
dev.off()
I still didn't get what they do. But adding either of them caused my code to stop.
I tried defining my 'for' loop function say call it 'XX', then later call it to make a list of graph but it returned NULL output.
I have tried defining an empty list (as I read in some answers here) then counting them to make a list that can be printed but I got so many errors.
I have done this for almost 3 days and will appreciate your help in resolving this.
Thanks!
I tried to complete your code ... and this works (but I don't have your 'stat.test' object). Basically, I added a graph3.i <- list() and replaced graph3.i in the loop ..
Is it what you wanted to do ?
library(magrittr)
library(dplyr)
library(rstatix)
library(ggplot2)
library(ggpubr)
data <- read.csv(url('http://raw.githubusercontent.com/Fridahnyakundi/Descriptives-in-R/master/Output3.csv'))
graph3 <- data %>% group_by(Firm_category) %>%
doo(
~ggboxplot(
data =., x = "Means.type", y = "means",
fill ="grey", palette = "npg", legend = "none",
ggtheme = theme_pubr()
),
result = "plots"
)
graph3
# Add statistical tests to each corresponding plot
graph3.i <- list()
Firm_category <- graph3$Firm_category
xx <- for(i in 1:length(Firm_category)){
graph3.i[[i]] <- graph3$plots[[i]] +
labs(title = Firm_category[i]) # +
# stat_pvalue_manual(stat.test[i, ], label = "p.adj.signif")
print(graph3.i)
}
library(cowplot)
print(plot_grid(plotlist = graph3.i[1:11], nrow = 4, ncol = 3))
I am trying to generate plots by looping, here is my code:
n <- unique(wide_data$Product.Code)[1:3]
for (i in n)
{
my.prod2 <- filter(tall_bind, Product.Code == i, Date > ymd("2012/04/01"))
dev.new()
mypath <- file.path("C:","R","SAVEHERE",paste("myplot_", i, ".jpg", sep = ""))
jpeg(file=mypath)
mytitle = paste("Plot for product", i)
p <- qplot(Date, Sold, data = my.prod2, geom = "line", main=mytitle, group = Model, colour = Model) + facet_grid(Model ~ .)
ggsave("myplot_", i, plot=p, device= "jpg" )
}
I get the following error for the above code:
Saving 6.67 x 6.67 in image
Error in ggsave("myplot_", i, plot = p, device = "jpg") : could
not find function "device"
Earlier when I used dev.off() at the end of the loop, I found that though the graphs were being generated they were totally blank.
Could someone please help me understand where is the mistake in my code?
You can leave out the dev.new() and jpg() commands, and also your arguments to ggsave() are incorrect. This should work:
n <- unique(wide_data$Product.Code)[1:3]
for (i in n) {
my.prod2 <- filter(tall_bind, Product.Code == i, Date > ymd("2012/04/01"))
mypath <- file.path("C:","R","SAVEHERE",paste("myplot_", i, ".jpg", sep = ""))
mytitle = paste("Plot for product", i)
p <- qplot(Date, Sold, data = my.prod2, geom = "line", main=mytitle, group = Model, colour = Model) + facet_grid(Model ~ .)
ggsave(filename = mypath, plot = p)
}
What you did was creating a new default graphics device, typically a plotting window, then a jpeg graphics device, i.e. a file. Then you tried to make ggplot2 to plot to directly to file using ggsave, i.e. using its own (jpg) device, and not using either of the two graphics devices you created.
The error, however, was because you gave ggsave the wrong arguments. But even with the right arguments, you would still have ended up with additional unused graphics windows and files through the dev.new() and jpeg() commands. I suggest some extra reading of the help (e.g. type ?ggsave at the r console).
Typically, when using ggplot2 you do not need to worry about dev.new, jpeg and the like. qplot or ggplot and ggsave should do all you need.
I am trying to save plots which have female (\u2640) and male (\u2642) symbols. Here is an example to create a plot using this symbols (I am using RStudio):
gender <- rbinom(n=100, size=100, prob=0.5)
plot(gender, cex=2.5,
pch=ifelse(gender %% 2 == 0, -0x2642L, -0x2640L),
col=ifelse(gender %% 2 == 0, 2, 3), main="\u2640 and \u2642 Symbols")
It works and generates a plot with those symbols Plot. I can save it as picture (PNG) but when I try to save it as pdf all the symbols don't show up Plot.
Here is how I try to save it as pdf:
pdf("plot.pdf")
gender <- rbinom(n=100, size=100, prob=0.5)
plot(gender, cex=2.5,
pch=ifelse(gender %% 2 == 0, -0x2642L, -0x2640L),
col=ifelse(gender %% 2 == 0, 2, 3), main="\u2640 and \u2642 Symbols")
dev.off()
I saw another post about similar problem here and it was suggested to use the CairoPDF. It did not work. I tried other family settings but it did not work either. Is there any other work around to save it as pdf with those symbols or the only way it is to save it as a picture. I would prefer to save it as pdf.
After a lot of tentatives I switched to command line and use quartz. After plotting the graph I use:
quartz.save(type = 'pdf', file = 'output.pdf')
It works perfectly. Why does it not works using the first code pdf("plot.pdf") but works with quartz.save(type = 'pdf', file = 'output.pdf')? Is it something with my system?
Thank you.
On my Mac this gives a pdf with astrological symbols. (Cobbled together from a search of similar questions on SO.) I didn't make the extra effort to "wrap" the full set neatly so the "printing of the later ones doesn't show up, but you can see Mars and Venus.
cairo_pdf("Venus_Mars.pdf",family="ArialUnicodeMS")
plot(1,1)
TestUnicode <- function(start="263c", end="2653", ...)
{
nstart <- as.hexmode(start)
nend <- as.hexmode(end)
r <- nstart:nend
s <- ceiling(sqrt(length(r)))
for(i in seq(r)) {
try(points(.6+(i/10), .8 , pch=-1*r[i],...))
}
}
TestUnicode()
dev.off()
I'm trying to make very simple GUI for my script. In nutshell problem looks like that :
dataset is dataframe, I would like to plot one column as the time and use simple GUI for choosing next/previus column.
dataset <-data.frame(rnorm(10), rnorm(10), rnorm(10))
columnPlot <- function(dataset, i){
plot(dataset[, i])
}
how to use tcltk for calling fplot with different i's ?
Not what you asked for (not tcltkrelated), but I would advise you to have a look at the new shiny package from RStudio.
Are you particularly attached to the idea of using tcltk? I've been working on something similar using the gWidgets package and have had some success. According to it's CRAN site, "gWidgets provides a toolkit-independent API for building interactive GUIs". This package uses tcltk or GTK2 and I've been using the GTK2 portion. Here's a quick example of a GUI with a spinbutton for changing i. I also added a little fanciness to your function because you mentioned you would be plotting time series, so I made the x axis Time.
data<-data.frame(rnorm(11),rnorm(11),rnorm(11))
i = 1
fplot <- function(i, data = data){
library(ggplot2)
TimeStart <- as.Date('1/1/2012', format = '%m/%d/%Y')
plotdat <- data.frame(Value = data[ ,i], Time = seq(TimeStart,TimeStart + nrow(data) - 1, by = 1))
myplot <- ggplot(plotdat, aes(x = Time, y = Value))+
geom_line()
print(myplot)
}
library(gWidgets)
options(guiToolkit = 'RGtk2')
window <- gwindow ("Time Series Plots", visible = T)
notebook <- gnotebook (cont = window)
group1 <- ggroup(cont = notebook, label = "Choose i", horizontal=F)
ichooser <- gspinbutton(cont = group1, from = 1, to = ncol(data), by = 1, value = i, handler = function(h,...){
i <<- svalue(h$obj)})
plotbutton <- gbutton('Plot', cont = group1, handler=function(h,...){
fplot(i, data)})
graphicspane1 <- ggraphics(cont = group1)