0byt3m1n1
Path:
C:
/
Users
/
Administrator
/
AppData
/
Local
/
RStudio
/
sources
/
session-d2b5bf0d
/
[
Home
]
File: D582E7B6-contents
library(shiny) library(dplyr) library(ggplot2) library(plotly) library(tidyr) library(zoo) library(lubridate) library(RColorBrewer) library(shinythemes) library(shinyWidgets) library(DiagrammeR) library(ggtext) # Read the daily rainfall data rainfall_data <- read.csv("rainfall_data.csv") # Clean and pre-process the data start_date <- as.Date("1987-01-01") end_date <- as.Date("2023-02-28") Date <- seq(from = start_date, to = end_date, by = "day") rainfall_data$Date <- Date rainfall_data$Date <- as.Date(rainfall_data$Date, format = "%Y-%m-%d") rainfall_data$Week <- week(rainfall_data$Date) rainfall_data$Month <- month(rainfall_data$Date) rainfall_data$Year <- year(rainfall_data$Date) # Group the data by Year and Month, and calculate the average rainfall for each group rainfall_data <- rainfall_data %>% group_by(Year, Month) %>% mutate(avg_rainfall = mean(rainfall)) # Remove missing values from the dataframe rainfall_data <- na.omit(rainfall_data) # Ungroup the data rainfall_data <- ungroup(rainfall_data) # Create a new variable indicating the season information rainfall_data <- rainfall_data %>% mutate(Season = ifelse(Month %in% c(12, 1, 2), "Winter", ifelse(Month %in% c(3, 4, 5), "Summer", ifelse(Month %in% c(6, 7, 8, 9), "South West Monsoon", "Post Monsoon")))) ## # Define UI ui <- navbarPage( title = HTML("<span style='font-size: 36px; color: #FFFFFF; font-family: Arial, sans-serif; font-weight: bold; text-shadow: 1px 1px #000000;'>Discover the Secrets of Rainfall: An Interactive Data Visualization Tool</span>"), theme = shinytheme("paper"), tags$head( tags$style( HTML(" body { background-image: url('https://cdn.pixabay.com/photo/2016/06/08/12/08/sea-1440809_960_720.jpg'); background-repeat: no-repeat; background-size: cover; background-position: center center; } .navbar-default { background-color: #1f2d3d; border-color: #1f2d3d; } .navbar-default .navbar-brand { color: #FFFFFF; } ") ) ), tabPanel(tags$h3("Home", style = "color: #fff; background-color: #007bff; padding: 10px; "), fluidPage( titlePanel("Welcome to Our Rainfall Insights Dashboard !"), mainPanel( tags$style(type="text/css", " h2 {color: #007bff; font-weight: bold; text-align: center; margin-top: 40px; margin-bottom: 40px;} h3 {color: #007bff; font-weight: bold;} p {font-size: 16px; color: #444444;} .about-panel {background-color: #f8f9fa; padding: 20px; border-radius: 10px; box-shadow: 0px 0px 15px #888888;} .header-logo {padding: 20px 0; text-align:center;} "), div(class = "about-panel", div( class = "header-logo", style = "filter: brightness(110%) contrast(80%) saturate(120%) hue-rotate(20deg);", img( src = "http://www.cwrdm.org/nexshop/themes/cwrdm/assets/img/cwrdm_header_iso.png", alt = "CWRDM Logo", height = "150px" ) ), tags$style( HTML(" .number-circle { display: inline-block; text-align: center; vertical-align: middle; width: 30px; height: 30px; border-radius: 50%; background-color: #007bff; color: white; font-weight: bold; font-size: 16px; margin-right: 10px; margin-bottom: 10px; } ol.no-numbers { list-style-type: none; } ") ), h3(style = "font-weight: bold; margin-top: 0; margin-bottom: 10px; font-size: 20px;color: #007bff;", "Pro Tips for Using Our Dashboard:"), tags$ol( class = "no-numbers", style = "margin-top: 0; margin-bottom: 0; font-size: 20px;", tags$li( style = "margin-bottom: 15px;", tags$span(class = "number-circle", "1"), icon("info-circle", lib = "font-awesome"), "Understand the data source, time period, and units." ), tags$li( style = "margin-bottom: 15px;", tags$span(class = "number-circle", "2"), icon("chart-bar", lib = "font-awesome"), "View rainfall overview for summary information." ), tags$li( style = "margin-bottom: 15px;", tags$span(class = "number-circle", "3"), icon("chart-line", lib = "font-awesome"), "Check seasonal analysis for trends and patterns." ), tags$li( style = "margin-bottom: 15px;", tags$span(class = "number-circle", "4"), icon("calendar", lib = "font-awesome"), "Adjust time period for analysis." ), tags$li( style = "margin-bottom: 5px;", tags$span(class = "number-circle", "5"), icon("chart-area", lib = "font-awesome"), "Compare data from different time periods." ), tags$li( style = "margin-bottom: 5px;", tags$span(class = "number-circle", "6"), icon("sliders-h", lib = "font-awesome"), "Use filters to refine data analysis." ), tags$li( style = "margin-bottom: 0;", tags$span(class = "number-circle", "7"), icon("bullseye", lib = "font-awesome"), "Interpret data for trends and patterns." ) ), br(), div( class = "rainfall-plots", h2("Rainfall Plots"), p("Explore the different ways to visualize rainfall data with our dashboard. Here are some examples:"), br(), div( class = "plot-section", h3("Annual Plot"), p("This chart shows the total amount of rainfall for each year in the selected date range. It can help users understand the general trend of rainfall over the years.") ), div( class = "plot-section", h3("Daily Plot"), p("This plot shows the amount of rainfall for each day in the selected date range. It can help users identify days with heavy rainfall, which may be useful for flood forecasting.") ), div( class = "plot-section", h3("Monthly Plot"), p("This plot displays the total amount of rainfall for each month in the selected date range. It can help users understand the monthly distribution of rainfall and identify any patterns or trends.") ), div( class = "plot-section", h3("Rainy day Plot"), p("This plot helps to identify the frequency of rainy days for each month in a given time period.") ), div( class = "plot-section", h3("Seasonal Decomposition Plot"), p("This plot decomposes a rainfall time series into its components, including trend, seasonal, and residual, and is useful in understanding the pattern of seasonality and trend over time.") ), div( class = "plot-section", h3("Seasonal Plot"), p("A seasonal plot is a type of data visualization that displays data over time, highlighting patterns and seasonal fluctuations in the data. It is commonly used in time series analysis.") ) ), br(), h2("About Kozhikode"), p("The selected study area of Kozhikode district in Kerala State, India, is located in the humid tropical region, which receives abundant rainfall of over 3000 mm annually, three times higher than the Indian national average. The district is situated between North latitudes 11° 08â² to 11° 50â² and East longitudes 75° 30â² to 76° 8â², covering parts of Survey of India Toposheets 58 A and 49 M. Kozhikode district is bordered by Kannur district to the north, Wayanad district to the east, Malapuram district to the south, and the Arabian Sea to the west. These factors contribute to the unique climatic conditions in the area, making it a vital region to monitor and analyze rainfall patterns."), br(), h2("About CWRDM"), p("The Centre for Water Resources Development and Management (CWRDM) plays a critical role in managing water resources in Kerala, where rainfall patterns can be unpredictable and extreme. CWRDM's research and development activities aim to understand the impact of rainfall on water resources, develop sustainable water management strategies, and provide technical support to government agencies and non-governmental organizations. CWRDM's hydrological and meteorological data collection and analysis systems provide valuable information on rainfall patterns, which can be used to forecast floods and droughts, and develop water conservation and management plans. CWRDM's expertise in water resources management, combined with its advanced research and development capabilities, makes it a valuable resource in addressing the challenges of managing water resources in a changing climate.") ) ) ) ), tabPanel(tags$h3("Rainfall Overview", style = "color: #fff; background-color: #007bff; padding: 10px;"), sidebarLayout( sidebarPanel( dateRangeInput("date_range", "Select Date Range:", start = min(rainfall_data$Date), end = max(rainfall_data$Date)), selectInput("month_range", "Select Month Range:", choices = c("All", month.name[1:12]), selected = "All"), selectInput("monthly_slicer", "Select a Month:", choices = c("", month.name[1:12])), actionButton("reset", "Reset Date and Month Range"), selectInput("season", label = "Select Season:", choices = c("All Seasons", "Winter", "Summer", "South West Monsoon", "Post Monsoon"), selected = "All Seasons") ), mainPanel( fluidRow( column(width = 6, plotOutput("annual_plot")), column(width = 6, plotlyOutput("monthly_trend")) ), fluidRow( column(width = 6, plotlyOutput("daily_plot")), column(width = 6, plotlyOutput("monthly_plot")) ) ) )), tabPanel(tags$h3("Seasonal Analysis", style = "color: #fff; background-color: #007bff; padding: 10px;"), sidebarLayout( sidebarPanel( selectInput("season", label = "Select Season:", choices = c("All Seasons", "Winter", "Summer", "South West Monsoon", "Post Monsoon"), selected = "All Seasons"), actionButton("reset_season", "Reset Seasonal Slicer") ), mainPanel( tabsetPanel( type = "tabs", tabPanel("Time Series Plot", plotOutput("tsplot")), tabPanel("Histogram", plotOutput("histogram")), tabPanel("Boxplot", plotOutput("boxplot")), tabPanel("Seasonal Decomposition", plotOutput("decomposition")) ) ) )), tabPanel(tags$h3("Contact Us", style = "color: #fff; background-color: #007bff; padding: 10px;"), fluidPage( titlePanel(tags$h1("Water is not just a resource, it's the source of life. - Rajendra Singh", style = "font-size: 36px;color: #1f2d3d;")), mainPanel( tags$style(type="text/css", " h2 {color: #007bff; font-size: 24px;} h3 {color: #6c757d; font-size: 20px; margin-top: 30px;} p {font-size: 18px; line-height: 1.5;} .contact-info {border: 1px solid #28a745; padding: 10px; background-color: #d4edda; border-radius: 5px;} .about-panel {background-color: #f8f9fa; padding: 20px; border-radius: 5px; box-shadow: 2px 2px 5px #888888;} .data-source {font-style: italic; color: #6c757d; margin-top: 10px;} "), div(class = "about-panel", h3(style="color: #007bff;", "Data Source"), p("The meteorological data used in this dashboard is collected from the Observatory located at CWRDM."), p(class = "data-source", "Source: CWRDM"), br(), h3(style="color: #007bff;", "Author"), p("This Rainfall Analysis Dashboard was created by Dr. Naveena K, a Scientist at CWRDM, with expert guidance from Dr. Surendran U."), br(), h3(style="color: #007bff;", "Contact"), div(class = "contact-info", p("Dr. Naveena K"), p("Scientist, LWMRG, CWRDM"), p("Email: naveenak@cwrdm.org")) )) )), ) # Define custom theme theme_custom <- function() { theme_bw(base_size = 14) + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), axis.line = element_line(colour = "black",size = 12), axis.text = element_text(colour = "black",size = 12), axis.title = element_text(colour = "black", size = 16), plot.title = element_text(colour = "black", size = 20), plot.background = element_rect(fill = ""), panel.background = element_rect(fill = "white")) } # Define server logic server <- function(input, output, session) { # Filter data based on selected date range and month range filtered_data <- reactive({ d <- rainfall_data %>% filter(Date >= input$date_range[1], Date <= input$date_range[2]) if (nrow(d) == 0) { return(data.frame()) } if (input$month_range != "All") { month_num <- match(input$month_range, month.name) d <- d %>% filter(Month == month_num) } if (input$monthly_slicer != "") { month_num <- match(input$monthly_slicer, month.name) d <- d %>% filter(Month == month_num) } d }) ##monthly rainyday plot output$monthly_plot <- renderPlotly({ filtered_data_monthly <- filtered_data() %>% mutate(Rainy_Day = ifelse(rainfall > 2.5, 1, 0)) %>% group_by(Year, Month) %>% summarise(Total_Rainy_Days = sum(Rainy_Day), .groups = "drop") %>% ungroup() if (nrow(filtered_data_monthly) == 0) { return(NULL) } if (input$monthly_slicer != "") { month_num <- match(input$monthly_slicer, month.name) filtered_data_monthly <- filtered_data_monthly %>% filter(Month == month_num) } # Define a color palette based on the number of months colors <- colorRampPalette(brewer.pal(n = 12, name = "Set3")) # Set the color of the bars based on the month colorscale <- colors(length(unique(filtered_data_monthly$Month))) p <- plot_ly(filtered_data_monthly, x = ~as.Date(paste(Year, Month, "1", sep = "-")), y = ~Total_Rainy_Days, type = "bar", marker = list(color = colorscale), showlegend = FALSE) p %>% layout(xaxis = list(title = "Date",font = list(size = 12, color = "black", family = "Arial Bold")), yaxis = list(title = "Total Rainy Days",font = list(size = 12, color = "black", family = "Arial Bold")), title = list(text = "Monthly Rainy Days", font = list(size = 18, color = "black", family = "Arial Bold")), margin = list(l = 60, r = 10, t = 80, b = 50), plot_bgcolor = "", paper_bgcolor = "white") }) # Annual rainfall plot output$annual_plot <- renderPlot({ filtered_data_annual <- filtered_data() %>% group_by(Year) %>% summarise(Total_Rainfall = sum(rainfall), .groups = "drop") %>% ungroup() if (nrow(filtered_data_annual) == 0) { return(NULL) } avg_rainfall <- mean(filtered_data_annual$Total_Rainfall) min_year <- min(filtered_data_annual$Year) plot <- ggplot(filtered_data_annual, aes(x = Year, y = Total_Rainfall, fill = Total_Rainfall)) + geom_col() + scale_fill_gradient(low = "blue", high = "lightblue") + geom_hline(yintercept = avg_rainfall, color = "red", linetype = "dashed") + annotate("text", x = min_year, y = avg_rainfall, label = "Average", color = "red", size = 3) + labs(title = "Annual Rainfall", x = "Year", y = "Rainfall (mm)", size = 14) + theme(plot.background = element_rect(fill = "white", color = NA), panel.background = element_blank(), plot.title = element_text(size = 20), legend.position = "none", plot.margin = unit(c(1,1,1,1), "cm")) + stat_smooth(method = "loess", formula = y ~ x, se = FALSE, color = "black") plot }) # Monthly rainfall trend plot output$monthly_trend <- renderPlotly({ filtered_data_monthly <- filtered_data() %>% group_by(Year, Month) %>% summarise(Total_Rainfall = sum(rainfall), .groups = "drop") %>% ungroup() if (nrow(filtered_data_monthly) == 0) { return(NULL) } # Calculate average rainfall avg_rainfall <- mean(filtered_data_monthly$Total_Rainfall) # Calculate linear regression lm_model <- lm(Total_Rainfall ~ ymd(paste0(Year, "-", Month, "-01")), data = filtered_data_monthly) r_squared <- round(summary(lm_model)$r.squared, 2) eq <- paste0("y = ", round(lm_model$coefficients[1], 2), " + ", round(lm_model$coefficients[2], 2), "x") plot <- ggplot(filtered_data_monthly, aes(x = as.Date(paste0(Year, "-", Month, "-01")), y = Total_Rainfall)) + geom_line(color = "blue") + geom_smooth(method = "lm", se = FALSE, color = "red", formula = y ~ x) + labs(title = paste0("Monthly Rainfall Trend - Average Rainfall: ", round(avg_rainfall, 2), " mm"), x = "Date", y = "Rainfall (mm)", color = "Trend") + theme_bw()+ theme(plot.title = element_text(size = 12)) + annotate("text", x = as.Date(paste0(max(filtered_data_monthly$Year), "-", max(filtered_data_monthly$Month), "-01")), y = max(filtered_data_monthly$Total_Rainfall), label = paste0("R-squared: ", round(r_squared, 2), " "), hjust = 1, vjust = 1, size = 3) + annotate("text", x = as.Date(paste0(min(filtered_data_monthly$Year), "-", min(filtered_data_monthly$Month), "-01")), y = max(filtered_data_monthly$Total_Rainfall), label = paste0(" Average:",round(avg_rainfall, 1),"mm"), hjust = 0, vjust = 1, size = 3) + annotate("text", x = as.Date(paste0(max(filtered_data_monthly$Year),"-",max(filtered_data_monthly$Month), "-01")), y = 0.9 * max(filtered_data_monthly$Total_Rainfall), label = paste0("y=",round(lm_model$coefficients[1], 1), "+",round(lm_model$coefficients[2], 1),"x"," "), size = 3, hjust = 0.5, vjust = 1) plotly::ggplotly(plot) %>% layout(title = "Monthly Rainfall Plot", xaxis = list(title = "Date"), yaxis = list(title = "Rainfall (mm)")) }) # Daily rainfall plot output$daily_plot <- renderPlotly({ filtered_data_daily <- filtered_data() %>% mutate(Date = as.Date(Date)) %>% group_by(Date) %>% summarise(Total_Rainfall = sum(rainfall), .groups = "drop") if (nrow(filtered_data_daily) == 0) { return(NULL) } p <- plot_ly(filtered_data_daily, x = ~Date, y = ~Total_Rainfall, type = "scatter", mode = "lines+markers", marker = list(size = 6), showlegend = FALSE) p %>% layout(xaxis = list(title = "Date", font = list(size = 12, color = "black", family = "Arial Bold")), yaxis = list(title = "Total Rainfall (mm)", font = list(size = 12, color = "black", family = "Arial Bold")), title = list(text = "Daily Rainfall", font = list(size = 18, color = "black", family = "Arial Bold")), margin = list(l = 60, r = 10, t = 80, b = 50), plot_bgcolor = "", paper_bgcolor = "white") }) # Filter data based on region and season inputs # Filter data based on selected season filtered_data <- reactive({ if (input$season == "All Seasons") { rainfall_data } else { subset(rainfall_data, Season == input$season) } }) output$tsplot <- renderPlot({ plot(filtered_data()$Date, filtered_data()$rainfall, type = "l", col = "blue", lwd = 2, main = "Rainfall Time Series Plot", xlab = "Date", ylab = "Rainfall (mm)", cex.axis = 1.2, cex.lab = 1.4) legend("topright", legend = "", col = "blue", lwd = 2, bty = "n") grid(col = "grey", lty = "dotted") }) output$histogram <- renderPlot({ ggplot(data = filtered_data(), aes(x = rainfall)) + geom_histogram(fill = "#0072B2", color = "#0072B2", alpha = 0.5) + geom_vline(aes(xintercept = mean(rainfall)), color = "#D55E00", linetype = "dashed", size = 1) + labs(title = "Rainfall Histogram", x = "Rainfall (mm)", y = "Frequency") + theme_bw() + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()) }) ###boxplot output$boxplot <- renderPlot({ ggplot(data = filtered_data(), aes(x = Season, y = rainfall, fill = Season)) + geom_boxplot(alpha = 0.7, outlier.color = NA) + geom_point(aes(x = Season, y = rainfall)) + labs(title = "Rainfall Boxplot", x = "Season", y = "Rainfall (mm)", fill = "Season", title.size = 20, x.text.size = 14, y.text.size = 14, legend.title.size = 14, legend.text.size = 12) + theme_bw(base_size = 14) + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), legend.position = "bottom", legend.direction = "horizontal") }) ##decomposition plot output$decomposition <- renderPlot({ ts_data <- ts(filtered_data()$rainfall, frequency = 12) decompose_data <- decompose(ts_data) # Convert decomposed data into a data frame df <- data.frame( Date = time(ts_data), Observed = decompose_data$x, Seasonal = decompose_data$seasonal, Trend = decompose_data$trend, Random = decompose_data$random ) df_long <- tidyr::pivot_longer(df, -Date, names_to = "Component", values_to = "Value") # Plot using ggplot ggplot(df_long, aes(x = Date, y = Value, color = Component)) + geom_line() + facet_wrap(~Component, ncol = 1, scales = "free_y") + labs(title = "Rainfall Seasonal Decomposition", x = "", y = "Rainfall (mm)", color = "Component") + theme_bw(base_size = 16) + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), legend.title = element_text(size = 18), legend.text = element_text(size = 16), plot.title = element_text(size = 20, face = "bold"), axis.title = element_text(size = 18, face = "bold"), axis.text = element_text(size = 12)) }) #Reset button observeEvent(input$reset, { updateDateRangeInput(session, "date_range", start = min(rainfall_data$Date), end = max(rainfall_data$Date)) updateSelectInput(session, "month_range", selected = "All") updateSelectInput(session, "monthly_slicer", selected = "") }) #reset button #reset button observeEvent(c(input$reset, input$reset_season), { updateSelectInput(session, "season", selected = "All Seasons") }) } #Run the application shinyApp(ui = ui, server = server)