Peter Nsanze - 1 year ago 100

R Question

I have 25 cars in a race doing 58 laps.

Static plot showing all 58 laps

I want to have a slider that I want to control the laps seen in a chart as x axis in a ggplot.

UI:

`sliderInput("lapsView",`

"Choose laps to view:",

min = 1,

max = 58,

value = 10)

SERVER:

`library(shiny)`

shinyServer(function(input, output) {

output$distPlot <- renderPlot({

f1<- read.csv("F1 2011 Turkey - Fuel Corrected Lap Times.csv", header = T)

str(f1)

library(ggplot2)

f1$Driver<-as.factor(f1$Driver)

p1 <- ggplot(data=f1,

aes(x = Lap, y= Lap.Time, colour = Driver)) +

ylim(80,100)+

geom_line() + geom_point()

# I combined p1 with p2 to save space.

p2 <- p1 + coord_polar()

p2

})

})

I'd like to change

`x=Lap`

`x = sliderInput`

I tried

`x = input$lapsView`

Please help.

Answer Source

If you really want to do it with a `sliderInput`

you could proceed as follows:

change the value of the parameter

`value`

in the`sliderInput`

from`10`

to a vector, say,`c(1, 58)`

create a sequence of integers with minimum and maximum value given by the ranged slider

`lapsView <- seq(input$lapsView[1], input$lapsView[2])`

do subsetting on

`f1`

. It is necessary because otherwise you would get vectors with a different length and ggplot wouldn't be happy with that yielding an error`f1_new <- f1[which(f1$Lap %in% lapsView), ]`

and finally use a new dataset in ggplot

**Ui.R**

```
sliderInput("lapsView",
"Choose laps to view:",
min = 1,
max = 58,
value = c(1, 58),
dragRange = TRUE) # the min and max can be dragged together
```

**Server.R**

```
library(shiny)
library(ggplot2)
shinyServer(function(input, output) {
output$distPlot <- renderPlot({
f1 <- read.csv("F1 2011 Turkey - Fuel Corrected Lap Times.csv", header = T)
# str(f1)
f1$Driver <- as.factor(f1$Driver)
lapsView <- seq(input$lapsView[1], input$lapsView[2])
# Subsetting:
f1_new <- f1[which(f1$Lap %in% lapsView), ]
p1 <- ggplot(data = f1_new,
aes(x = Lap, y = Lap.Time, colour = Driver)) +
ylim(80, 100)+
geom_line() + geom_point()
p2 <- p1 + coord_polar()
p2
})
})
```