Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Real-time auto incrementing ggplot in R

Tags:

plot

r

ggplot2

This thread answers how to create incremental plots in R with a real-time effect.

I want to do the same thing with ggplot2 instead of R's base plot. Directly copying from the answer in that link, I tried this but it didn't work:

n=1000
df=data.frame(time=1:n,y=runif(n))
window=100
for(i in 1:(n-window)) {
  print(i)
  flush.console()
  ggplot(df) + geom_line(aes(x=time, y=y), size=0.7) + xlim(i,i+window)
  Sys.sleep(.09)
}

I guess the image rendering for ggplot2 works differently. Is it possible to create a real-time updating effect with ggplot2?

Ideally, I want to be able to display multiple geom_lines. But I guess the logic will be the same.

Also, is it possible to achieve this when the plot is "Zoom"ed in in R-Studio?

like image 428
Zhubarb Avatar asked Nov 29 '14 18:11

Zhubarb


People also ask

What does Geom_point () do in R?

The function geom_point() adds a layer of points to your plot, which creates a scatterplot.

What is Geom_line in ggplot?

geom_line() connects them in order of the variable on the x axis. geom_step() creates a stairstep plot, highlighting exactly when changes occur. The group aesthetic determines which cases are connected together.

What is GG in ggplot?

ggplot2 is a system for declaratively creating graphics, based on The Grammar of Graphics. You provide the data, tell ggplot2 how to map variables to aesthetics, what graphical primitives to use, and it takes care of the details.

Which argument of ggplot can be used to add Customisation to plots?

To customize the plot, the following arguments can be used: alpha, color, fill and dotsize. Learn more here: ggplot2 dot plot.


1 Answers

It's not clear where you're going with this, but this code will produce an HTML animation that renders smoothly. It will take a while (about a minute) to create the animation though.

library(animation)
library(ggplot2)
# your data
n  <- 1000
df <- data.frame(time=1:n,y=runif(n))
window <- 100
# create the animation
saveHTML({
for(i in 1:(n-window)) {
  print(ggplot(df) + geom_line(aes(x=time, y=y), size=0.7) + xlim(i,i+window))
}
})
like image 86
jlhoward Avatar answered Sep 30 '22 03:09

jlhoward