t00T t00T - 29 days ago 16
R Question

R: Stabilizing scatter plot with shiny and ggplot2

What I am trying to do is create a shiny app that plots my x and y for each obs on a scatter plot as it cycles through a time variable(t).

grph dataframe:

id x y t
1 3 8 3
2 6 2 8
3 2 6 1
1 9 4 5


server.R

library(shiny)
library(ggplot2)

function(input, output) {
#Store data into df for plotting
df <- data.frame(grph, header = TRUE)

#Plot output
output$plot <- renderPlot({
dt<-cbind(df,Ftime=as.numeric(df$t))
dt<-dt[dt$Ftime==input$t,]

if(nrow(dt)==0) ggplot(df, aes(x,y))
else ggplot(dt,aes(x,y))+geom_point()
})
}


ui.R

library(shiny)
library(ggplot2)

fluidPage(
#Sidebar header
headerPanel('Demo'),
#Sidebar panel
sidebarPanel(
#Animated sidebar (time converted to mins)
sliderInput("t", "Time",
min = 0,
max = 1440,
value = 0, step=1,
animate=
animationOptions(interval=1000, loop=TRUE))
),
#Export graph to main panel
mainPanel(
plotOutput('plot')
)
)


It is working for the most part but I currently have two problems: (1) I am having trouble stabilizing my scatter plot since it is constantly changing my max and min for both x and y on the graph and (2) Every now and then it will blur out the graph. Here is an example

Answer Source

(1) I am having trouble stabilizing my scatter plot since it is constantly changing my max and min for both x and y on the graph

You can use the same df to set the bounds, and then provide the subset dataset within geom_point.

ggplot(df,aes(x,y)) + geom_point(data = dt)

Alternatively, you can use coord_cartesian() and pass the min/max for the full dataset:

ggplot(dt, aes(x,y)) + 
  geom_point() +
  coord_cartesian(xlim = c(min(df$x), max(df$x)),
                  ylim = c(min(df$y), max(df$y)))

(2) Every now and then it will blur out the graph.

Your plotting is not able to keep up with the rate of animation. You can adjust the interval.

animationOptions(interval = 1000, loop = FALSE, playButton = NULL,
pauseButton = NULL)

# Animation with custom interval (in ms) to control speed, plus looping
    sliderInput("animation", "Looping Animation:", 1, 2000, 1, step = 10, 
                animate=animationOptions(interval=300, loop=T))