Bắt đầu ngayBắt đầu miễn phí

Biến biểu đồ của bạn thành tương tác

plotly là một gói phổ biến để tạo biểu đồ tương tác trong Shiny. Có một số gói khác cho trực quan hóa tương tác, nhưng chúng ta sẽ dùng plotly chủ yếu vì hàm ggplotly(), hàm này chuyển một biểu đồ ggplot2 thành biểu đồ tương tác.

Bài tập này là một phần của khóa học

Nghiên cứu tình huống: Xây dựng ứng dụng web với Shiny trong R

Xem khóa học

Hướng dẫn bài tập

Mã cho ứng dụng Shiny từ bài tập trước đã được cung cấp. Nhiệm vụ của bạn là thay biểu đồ ggplot2 bằng biểu đồ plotly. Cụ thể:

  • Nạp gói plotly.
  • Thay hàm xuất biểu đồ bằng plotlyOutput (dòng 20).
  • Thay hàm render biểu đồ bằng renderPlotly (dòng 29).
  • Chuyển biểu đồ ggplot2 hiện có sang biểu đồ plotly (dòng 31).

Bài tập tương tác thực hành trực tiếp

Hãy thử làm bài tập này bằng cách hoàn thành đoạn mã mẫu này.

# Load the plotly package
___

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      textInput("title", "Title", "GDP vs life exp"),
      numericInput("size", "Point size", 1, 1),
      checkboxInput("fit", "Add line of best fit", FALSE),
      colourInput("color", "Point color", value = "blue"),
      selectInput("continents", "Continents",
                  choices = levels(gapminder$continent),
                  multiple = TRUE,
                  selected = "Europe"),
      sliderInput("years", "Years",
                  min(gapminder$year), max(gapminder$year),
                  value = c(1977, 2002))
    ),
    mainPanel(
      # Replace the `plotOutput()` with the plotly version
      plotOutput("plot")
    )
  )
)

# Define the server logic
server <- function(input, output) {
  # Replace the `renderPlot()` with the plotly version
  output$plot <- renderPlot({
    # Convert the existing ggplot2 to a plotly plot
    ___({
      data <- subset(gapminder,
                     continent %in% input$continents &
                       year >= input$years[1] & year <= input$years[2])
      
      p <- ggplot(data, aes(gdpPercap, lifeExp)) +
        geom_point(size = input$size, col = input$color) +
        scale_x_log10() +
        ggtitle(input$title)
      
      if (input$fit) {
        p <- p + geom_smooth(method = "lm")
      }
      p
    })
  })
}

shinyApp(ui = ui, server = server)
Chỉnh sửa và Chạy Mã