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_line
s. 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?
The function geom_point() adds a layer of points to your plot, which creates a scatterplot.
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.
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.
To customize the plot, the following arguments can be used: alpha, color, fill and dotsize. Learn more here: ggplot2 dot plot.
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))
}
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With