시작하기무료로 시작하기

그래프를 대화형으로 만들기

plotly는 Shiny에서 대화형 그래프를 만드는 데 널리 쓰이는 패키지입니다. 대화형 시각화를 위한 다른 패키지도 여럿 있지만, 우리는 주로 ggplotly() 함수 때문이에 plotly를 사용합니다. 이 함수는 ggplot2 그래프를 대화형 그래프로 변환해 줍니다.

이 연습은 강의의 일부입니다

사례 연구: R의 Shiny로 웹 애플리케이션 만들기

강의 보기

연습 안내

이전 연습 문제의 Shiny 앱 코드가 제공되어 있습니다. 할 일은 ggplot2 그래프를 plotly 그래프로 바꾸는 것입니다. 구체적으로:

  • plotly 패키지를 불러오세요.
  • 그래프 출력 함수는 plotlyOutput으로 바꾸세요(20행).
  • 그래프 렌더 함수는 renderPlotly로 바꾸세요(29행).
  • 기존 ggplot2 그래프를 plotly 그래프로 변환하세요(31행).

실습형 인터랙티브 연습

이 예제를 이 샘플 코드를 완성하여 풀어보세요.

# 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)
코드 편집 및 실행