library(readxl)
library(ggplot2)
library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.4     ✔ readr     2.1.5
## ✔ forcats   1.0.0     ✔ stringr   1.5.1
## ✔ lubridate 1.9.3     ✔ tibble    3.2.1
## ✔ purrr     1.0.2     ✔ tidyr     1.3.1
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(plotly)
## 
## 다음의 패키지를 부착합니다: 'plotly'
## 
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## 
## The following object is masked from 'package:stats':
## 
##     filter
## 
## The following object is masked from 'package:graphics':
## 
##     layout
library(shiny)

data <- read_xlsx("c://R432/hw_pop.xlsx")
## New names:
## • `` -> `...1`
pop <- data %>% 
  rename("city" = "...1") %>% 
  rename_all(~ ifelse(. != "city", paste0("X", .), .))

# # UI 간단 구성
# ui <- fluidPage(
#   titlePanel("화순군 읍면별 인구 변화"),
#   sidebarPanel(
#     # 지역 선택
#     selectInput("region", "지역 선택", choices = c("화순읍", "기타"), selected = "화순읍", width = "50%")
#   ),
#   mainPanel(
#     plotlyOutput("population", width = "100%" ),
#     plotlyOutput("households", width = "100%" )
#   )
# )
# UI 구성
ui <- fluidPage(
  titlePanel("화순군 읍면별 인구 변화"),
  fluidRow(
    column(
      width = 3,  # sidebarPanel의 초기 너비
      sidebarPanel(
        # 지역 선택
        selectInput("region", "지역 선택", choices = c("화순읍", "기타"), selected = "화순읍", width="100%")
      )
    ),
    column(
      width = 9,  # mainPanel의 초기 너비
      # mainPanel 내용
      plotlyOutput("population", width = "100%" ),
      plotlyOutput("households", width = "100%" )
    )
  )
)

# 서버 구성
server <- function(input, output) {
  pop <- pop %>% 
    select(city, contains("population_subtot") | contains("households")) %>% 
    mutate(across(contains("population_subtot") | contains("households"), as.integer))
  # 화순읍 인구수, 세대수
  filtered_data <- reactive({
    if(input$region == "화순읍"){         # 화순읍 인구수, 세대수
      filtered_data1 <- pop %>% 
        select(city, contains("population_subtot")) %>% 
        filter(city == "화순읍") %>% 
        pivot_longer(cols = contains("population_subtot"),
                     names_to = "year",
                     values_to = "value")%>%
        # mutate(year = str_extract(year, "\\d+"))
        mutate(year = str_extract(year, "(?<=X)\\d+"))
      filtered_data2 <- pop %>% 
        select(city, contains("households")) %>% 
        filter(city == "화순읍") %>% 
        pivot_longer(cols = contains("households"),
                     names_to = "year",
                     values_to = "value")%>%
        mutate(year = str_extract(year, "(?<=X)\\d+"))
      return(list(filtered_data1 = filtered_data1, filtered_data2 = filtered_data2))
    } else {                          
      # 기타 인구수, 세대수
      filtered_data1 <- pop %>% 
        select(city, contains("population_subtot")) %>% 
        filter(city != "화순읍") %>% 
        pivot_longer(cols = contains("population_subtot"),
                     names_to = "year",
                     values_to = "value")%>%
        mutate(year = str_extract(year, "(?<=X)\\d+"))
      filtered_data2 <- pop %>% 
        select(city, contains("households")) %>% 
        filter(city != "화순읍") %>% 
        pivot_longer(cols = contains("households"),
                     names_to = "year",
                     values_to = "value")%>%
        mutate(year = str_extract(year, "(?<=X)\\d+"))
      return(list(filtered_data1 = filtered_data1, filtered_data2 = filtered_data2))
    }
  })

  # 그래프 생성 함수
  generate_plot <- function(data,ylab_text) {
    p <- ggplot(data, aes(x = year, y = value)) +
      geom_line(aes(group = city, color = city)) +
      geom_point(aes(group = city, color = city), size = 2) +
      geom_text(aes(label = value, group = city, color = city), position = position_nudge(y = 50), size=3) +
      xlab("연도") +
      ylab(ylab_text) +
      ggtitle("화순군 읍면별 인구 변화") +
      theme_minimal()
    
    ggplotly(p)
  }
  
  # 그래프 출력
  output$population <- renderPlotly({
    # 필터링된 데이터 사용하여 그래프 생성
    generate_plot(filtered_data()$filtered_data1, "인구수")
  })
  output$households <- renderPlotly({
    # 필터링된 데이터 사용하여 그래프 생성
    generate_plot(filtered_data()$filtered_data2, "세대수")
  })
  
}

# R Graphics 디바이스 설정(R graphics device(2)가 뜨지 않도록 설정.)
# options(device = "png")

# 앱 실행
shinyApp(ui = ui, server = server)
Shiny applications not supported in static R Markdown documents