본문 바로가기
데이터분석/R

[R 데이터분석 with 샤이니] 여러 지역 아파트가격 상관관계 비교 (Shiny)

by 버섯도리 2022. 7. 26.

> ## 12-1 여러 지역 상관관계 비교하기

> # Step 1 : 데이터 준비하기

> setwd(dirname(rstudioapi::getSourceEditorContext()$path))
> load("./06_geodataframe/06_apt_price.rdata") # 아파트 실거래 데이터
> library(sf)
> apt_price <- st_drop_geometry(apt_price)
> apt_price$py_area <- round(apt_price$area / 3.3, 0) # 크기 변환 (㎡ -> 평)
> head(apt_price[,c("area","py_area")])
  area py_area
1  130      39
2  145      44
3  175      53
4  175      53
5  123      37
6  123      37

> # Step 2 : 사용자 화면 구현하기


> library(shiny)
> library(ggpmisc)
> ui <- fluidPage(
+   titlePanel("여러 지역 상관관계 비교"),
+   fluidRow(
+     column(6,
+            selectInput(
+              inputId = "region",
+              label = "지역을 선택하세요",
+              unique(apt_price$addr_1),
+              multiple = TRUE
+            )),
+     column(6,
+            sliderInput(
+              inputId = "range_py",
+              label = "평수를 선택하세요",
+              min = 0,
+              max = max(apt_price$py_area),
+              value = c(0, 30)
+            )),
+     column(12,
+            plotOutput(outputId = "gu_plot", height = "600"))
+   )
+ )

> # Step 3 : 서버 구현하기

> server <- function(input, output, session) {
+   #---# 반응식
+   apt_sel <- reactive({
+     subset(apt_price,
+            addr_1 == unlist(strsplit(paste(input$region, collapse = ','), ",")) &
+              py_area >= input$range_py[1] & py_area <= input$range_py[2])
+   })
+   #---# 지역별 회귀선 그리기
+   output$gu_plot <- renderPlot({
+     if (nrow(apt_sel()) == 0)
+       return(NULL)
+     ggplot(apt_sel(), aes(x = py_area, y = py, col = "red")) +
+       geom_point() +
+       geom_smooth(method = "lm", col = "blue") +
+       # facet_wrap(~addr_1) => addr_1 별로 플롯을 그려준다.
+       # 지역별로 Y축 값이 달라질 수 있으면 free_y 옵션을 사용하며, 한 행에 3개씩 그리도록 설정한다.
+       facet_wrap(~addr_1, scale = "free_y", ncol = 3) +
+       theme(legend.position = "none") +
+       xlab("크기(평)") +
+       ylab("평당 가격(만원)") +
+       # stat_poly_eq 함수로 회귀선 차트 위에 회귀식을 표현해 준다.
+       stat_poly_eq(aes(label = paste(..eq.label..)),
+                    label.x = "right", label.y = "top",
+                    formula = y ~ x, parse = TRUE, size = 5, col = "black")
+   })
+ }

> # Step 4 : 애플리케이션 실행하기

> shinyApp(ui = ui, server = server)

Listening on http://127.0.0.1:5417



 

 

 

 

 

 

출처 : 김철민, ⌜공공데이터로 배우는 R 데이터분석 with 샤이니⌟, 이지스퍼블리싱, 2022