jeudi 27 février 2020

Select People to Show on a Plot Using checkboxGroupInput in Shiny

I want to use Shiny to build an interactive plot of my "Phone Usage" data - 5 students' hours of phone usage during a week (from 2/20 to 2/26).

Name    2.20    2.21    2.22    2.23    2.24    2.25    2.26
Minruo  6.05    5.53    6.47    5.47    5.87    7.80    5.70
Xudian  6.18    6.70    5.50    5.42    5.50    6.12    6.77
Luyi    12.53   18.77   12.72   9.80    10.95   9.57    11.08
Xiaojue 6.78    6.88    6.91    5.66    6.18    5.43    6.66
Ziyuan  15.45   19.25   14.48   15.25   7.47    9.42    10.52

I want to use checkboxGroupInput to select students to show on the plot. Without the code of checkboxGroupInput, the code below can produce a plot smoothly. However, an error "Breaks and labels are different lengths" occurred after I add checkboxGroupInput.

library(ggplot2)
library(plotly)
library(shiny)

# Define UI for application that draws a histogram
ui <- fluidPage(
    titlePanel("Phone Usage Time"),
    # select students to display on plot -> error occurred
    checkboxGroupInput("names", "Students to show:",
                     c("Luyi", "Minruo", "Xiaojue", "Xudian", "Ziyuan")),
    plotlyOutput("plot")
)

# Define server logic required to draw a histogram
server <- function(input, output) {
      output$plot <- renderPlotly({
        # load data
        phone_time <- read.csv("PhoneTime.csv")
        colnames(phone_time) <- c("Name", 2.20, 2.21, 2.22, 2.23, 2.24, 2.25, 2.26)
        # wide to long
        phone_df <- tidyr::gather(phone_time, date, usage_time, 2:8)
        phone_df$date <- as.numeric(phone_df$date)
        # change column name
        colnames(phone_df) <- c("Student.Name", "Date","Usage.Time")
        # subset by student -> where things go wrong!
        phone_sub <- phone_df[which(phone_df$Student.Name == input$names), ]

        # interactive plot
          ggplotly(
            ggplot(phone_sub) + 
              geom_point(aes(x = Date, y = Usage.Time, color = Student.Name)) +
              geom_line(aes(x = Date, y = Usage.Time, color = Student.Name)) +
              labs(title = "Daily Phone Usage Time in a Week", x = "Date", y = "Usage Time") +
              scale_x_continuous(breaks = seq(2.20, 2.26, 0.01), 
                           labels = c("2.20", "2.21", "2.22", "2.23", "2.24", "2.25", "2.26")) +
              ylim(5, 20) +
              theme_bw()
          )
    })
}

# Run the application 
shinyApp(ui = ui, server = server)



Aucun commentaire:

Enregistrer un commentaire