시작하기무료로 시작하기

데이터 시각화

그래프는 출력 객체이므로 Shiny 앱에서는 plotOutput() + renderPlot() 함수로 추가합니다. 출력 함수는 UI에 추가해 그래프의 위치를 지정하고, 서버 코드의 렌더 함수는 그래프를 생성합니다.

이제 1인당 GDP와 기대수명의 관계를 나타내는 그래프를 앱에 추가해 보세요. 이 그래프에 사용되는 데이터는 테이블에 표시된 데이터와 동일해야 합니다. 즉, 입력 필터와 일치하는 레코드만 그래프에 표시되어야 합니다. renderPlot() 내부의 코드는 renderTable() 내부에서 정의된 변수에 접근할 수 없으므로, 동일한 코드를 그대로 복사해 재사용해야 합니다. 이후에는 이러한 중복을 피하는 방법을 배우게 됩니다.

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

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

강의 보기

연습 안내

  • UI에 ID가 "plot"인 그래프 출력 자리 표시자를 추가하세요.
  • 서버에서 적절한 렌더 함수를 사용해 그래프를 생성하세요(30행).
  • 출력 테이블이 사용하는 것과 동일한 데이터 필터링 코드를 그래프 데이터에도 재사용하세요(32행).

실습형 인터랙티브 연습

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

ui <- fluidPage(
  h1("Gapminder"),
  sliderInput(inputId = "life", label = "Life expectancy",
              min = 0, max = 120,
              value = c(30, 50)),
  selectInput("continent", "Continent",
              choices = c("All", levels(gapminder$continent))),
  # Add a plot output
  ___(___),
  tableOutput("table")
)

server <- function(input, output) {
  output$table <- renderTable({
    data <- gapminder
    data <- subset(
      data,
      lifeExp >= input$life[1] & lifeExp <= input$life[2]
    )
    if (input$continent != "All") {
      data <- subset(
        data,
        continent == input$continent
      )
    }
    data
  })

  # Create the plot render function  
  output$plot <- ___({
    # Use the same filtered data code that the table uses
    data <- ___
            ___
            ___
    ggplot(data, aes(gdpPercap, lifeExp)) +
      geom_point() +
      scale_x_log10()
  })
}

shinyApp(ui, server)
코드 편집 및 실행