2016-08-07 4 views
2

У меня есть 25 автомобилей в гонке, выполняющих 58 кругов.R Блестящее приложение sliderInput control x axis в GGplot

Static plot showing all 58 laps

Я хочу иметь ползунок, который я хочу, чтобы контролировать круги видели на графике как ось й в 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 

    }) 

}) 

Я хотел бы изменить x=Lap по существу x = sliderInput. Я пробовал x = input$lapsView, но получаю только одну точку для каждого.

Пожалуйста, помогите.

Result

ответ

2

Если вы действительно хотите сделать это с sliderInput вы можете сделать следующее:

  • изменить значение параметра value в sliderInput от 10 к вектору c(1, 58)

  • создать последовательность целых чисел с минимальным и максимальным значениями, заданными ползунком дальности

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

  • сделать Подменю на f1. Это необходимо потому, что в противном случае вы получите векторы с разной длиной и ggplot пожалуется

    f1_new <- f1[which(f1$Lap %in% lapsView), ]

  • , наконец, использовать новый набор данных в ggplot

Ui.R

sliderInput("lapsView", 
       "Choose laps to view:", 
       min = 1, 
       max = 58, 
       value = c(1, 58), 
       dragRange = TRUE), 

    checkboxGroupInput("driverID", 
        "Driver", 
        c("Sebastian Vettel" = 1, "Mark Webber" = 2, 
         "Fernando Alonso" = 3, "Lewis Hamilton" = 4, 
         5, 6, 7, 8, 9, 10, 11, 12 ,13 ,14, 15, 16, 17, 18, 19, 20, 21, 22, 23,24,25), 
        selected = FALSE, inline = FALSE, width = NULL) 

Server.R

library(shiny) 
library(DT) 
server <- shinyServer(function(input, output) { 

    output$distPlot <- renderPlot({ 

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

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

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

     # driverID <- seq(input$driverID[1], input$driverID[2]) 
     driverID <- input$driverID 
     req(driverID) # require that driverID is not NULL - it would break down the code below 

     # Subsetting: 
     f1_new <- f1[which(f1$Lap %in% lapsView & f1$Driver %in% driverID),] 
     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 

    }) 

    observe({ 
     # input$lapsView returns in this case two values - minimum and maximum 
     # (initially 1 and 58) 
     # If we used these values we would have only two points - 1 and 58 
     # As we want to have all points in between 1 and 58 we create a sequence 
     # with the function `seq`. 
     # If you wanted to have a sequence in which starting value differs and 
     # maximum is always given by 58 you could do following: 

     # sliderInput: 
     # - remove dragRange = TRUE 
     # - change value from c(1,58) to 1 
     # server 
     # - lapsView <- seq(input$lapsView[1], 58) 


     # You want to add another condition to subsetting. It looks fine but 
     # you should change 
     # driverID <- seq(input$driverID[1], input$driverID[2]) 
     # to 
     # driverID <- input$driverID 
     # because input$driverID alrady contains all choices 
     # You have to be careful about the case when there is nothing checked. 
     # driverID yields in this case NULL 
     # It may break down the code so it is good to use the function `req` 


     # Here you can observe values of inputs in the console. It is a 
     # good way to see "what's going on" and to debug the code. 

     print(" ================================================== ") 
     print("Input$driverID") 
     print(input$driverID) 

     print("---------------") 
     print("input$lapsView") 
     print(input$lapsView) 
     # two values - min and max 

     print(" ================================================== ") 
     print('') 
     print('') 
     print('') 

    }) 

    }) 
+1

Удивительно! Спасибо огромное! –

+0

Не могли бы вы объяснить эту часть? 'создать последовательность целых чисел с минимальным и максимальным значениями, заданными ползунком диапазона lapsView <- seq (ввод $ lapsView [1], ввод $ lapsView [2])'. Я ожидал, что сделаю полный seq до ввода $ lapsView [58]. –

+0

Я хочу сделать аналогичную вещь, где имена драйверов, как опции флажка, могут фильтровать представление графика: checkboxGroupInput ("driverID", '" Driver ", c (" Sebastian Vettel "= 1," Mark Webber "= 2," Фернандо Алонсо "= 3," Льюис Хэмилтон "= 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,24,25), выбран = FALSE, инлайн = FALSE, то ширина = NULL) ' –

Смежные вопросы