--- title: "25 Million Trees Initiative Survey Report" author: - name: Nicholas Hepler affiliation: Office of Information Technology Services - name: Annabel Gregg affiliation: Department of Environmental Convervation date: "`r format(Sys.Date(), '%B, %d, %Y')`" keywords: "keyword1, keyword2" output: html_document: toc: true toc_depth: 1 toc_float: true number_sections: false css: custom.css code_folding: hide --- ```{r setup, include=FALSE} knitr::opts_chunk$set( echo = TRUE, message = FALSE, warning = FALSE ) # Load necessary libraries #library(dplyr) #library(ggplot2) library(knitr) library(lubridate) library(RColorBrewer) library(scales) library(sf) library(tidyverse) library(tigris) library(viridis) # Load survey data files from CSV as tibbles. survey_data <- read_csv("data/_25_Million_Trees_Initiative_Survey_0.csv") location_points <- read_csv("data/location_points_1.csv") location_polygons <- read_csv("data/location_polygons_2.csv") participant_organizations <- read_csv("data/participant_organizations_3.csv") species_planted <- read_csv("data/species_planted_4.csv") vendors <- read_csv("data/vendors_5.csv") # Transform date stored as character or numeric vectors to POSIXct objects. survey_data <- survey_data %>% mutate(CreationDate = mdy_hms(CreationDate)) # Count the records to be excluded (Exclude Result == 1) excluded_count <- survey_data %>% filter(`Exclude Result` == 1) %>% nrow() # Count the records that are used (Exclude Result == 0) used_count <- survey_data %>% filter(`Exclude Result` == 0) %>% nrow() # Ignore excluded data. survey_data <- survey_data %>% filter(`Exclude Result` == 0) # Join the data based on the ParentGlobalID, ensuring all rows from survey_data are retained combined_data <- survey_data %>% left_join(location_points, by = c("GlobalID" = "ParentGlobalID")) %>% left_join(location_polygons, by = c("GlobalID" = "ParentGlobalID")) %>% left_join(participant_organizations, by = c("GlobalID" = "ParentGlobalID")) %>% left_join(species_planted, by = c("GlobalID" = "ParentGlobalID")) %>% left_join(vendors, by = c("GlobalID" = "ParentGlobalID")) ``` --- subtitle: "`r format(min(survey_data$CreationDate, na.rm = TRUE), "%B %d, %Y")` to `r format(max(survey_data$CreationDate, na.rm = TRUE), "%B %d, %Y")`." --- # Report Overview {.tabset} [Back to Top](#) ## Background The **25 Million Trees Initiative** is a bold commitment launched by **Governor Kathy Hochul** during the 2024 State of the State Address, aiming to plant 25 million trees by 2033 in New York State. This initiative recognizes the critical importance of trees and forests for climate mitigation, enhancing community health, and supporting biodiversity. The New York State Department of Environmental Conservation (DEC) is at the forefront of tracking the progress of this ambitious goal. As part of this effort, DEC has launched the **Tree Tracker**, a tool for the public to record the trees they plant. These submissions contribute valuable data on the number, type, and locations of trees being planted across the state, helping to build a comprehensive, real-time dashboard of tree planting activities. This report compiles the survey data collected via the Tree Tracker and provides detailed insights into the information submitted by New Yorkers. It aims to support DEC staff and executives in understanding the progress of the initiative and identifying areas for improvement in outreach and engagement. ## Purpose & Objectives This report serves to present an overview of the data collected through the 25 Million Trees Initiative, offering insights into submission patterns, geographic distribution, and trends in tree planting activities. The report aims to: - Summarize the overall progress of the initiative. - Provide detailed data analysis on the submitted tree planting information. - Identify areas where more outreach or support may be needed. As more individuals contribute their data to the Tree Tracker, the initiative's success will be better understood, and DEC can better align resources to further promote this critical program. ## Survey Period & Exclusions The report covers the survey period from **`r format(min(survey_data$CreationDate, na.rm = TRUE), "%B %d, %Y")`** to **`r format(max(survey_data$CreationDate, na.rm = TRUE), "%B %d, %Y")`**, including a total of **`r excluded_count + used_count`** records. Out of these, **`r used_count`** records were deemed valid and included in the analysis. Exclusions were applied to **`r excluded_count`** records, which were removed due to various reasons, such as: - **Double Count**: Some submissions were identified as duplicates and excluded to prevent data redundancy. - **Test Data**: Entries that were intended solely for testing purposes were excluded, as they do not represent actual survey data. These excluded records are marked with a value of **1** in the `Exclude Result` field. The remaining **`r used_count`** records, marked with a **0**, represent legitimate data points that were included in the analysis. ## Validation & Data Consistency To ensure data integrity, several validation steps are applied to survey submissions: - **Required Fields**: - **Who Planted the Tree(s)?**: Describes the participant's role in the tree planting effort. - **Number of Trees**: The number of trees planted during the planting period. - **Start Date of Planting**: The date when planting began. - **End Date of Planting**: The date when planting was completed. - **Location**: Geographic coordinates (latitude and longitude). - **Response Validation**: - **Geographic Validation**: Once geographic coordinates are entered, they are checked against official civil boundaries to provide an accurate nominal locality, county, and region data. In rare cases, this check may fail due to service dependency, but such records are corrected before inclusion in the analysis. - **Date Validation and Logic**: Users cannot enter planting dates prior to the start date of the initiative. The system enforces this restriction, and any records with such dates are not allowed to be submitted. Additionally, users cannot enter a planting end date that occurs before the planting start date. - **Optional Questions**: Even optional questions undergo validation to ensure the entered data meets the expected format or logic, providing further consistency and accuracy. - **Email Format**: The email addresses entered in the survey are validated to ensure they follow the correct format. By applying these validation checks, the integrity and consistency of the data is ensured, allowing for meaningful analysis of tree planting surveys. # Submission Analysis {.tabset} [Back to Top](#) ```{r func-create_histogram, echo=TRUE, message=FALSE} create_histogram <- function(data, field, x_labels = NULL, color_palette = c("#154973", "#457aa5", "#eff6fb", "#face00"), title = NULL, x_title = NULL, y_title = "Count", max_label_count = 10, label_angle = 45, show_labels = TRUE) { # Default color palette primary_color <- color_palette[1] secondary_color <- color_palette[2] tertiary_color <- color_palette[3] accent_color <- color_palette[4] # Set default labels if not provided if (is.null(title)) title <- paste("Distribution of", field,) if (is.null(x_title)) x_title <- field # Plot ggplot(data, aes(x = .data[[field]])) + geom_bar(fill = primary_color, color = secondary_color, stat = "count") + # Add text labels, but conditionally hide small bars if specified (if (show_labels) geom_label(stat = "count", aes(label = scales::comma(after_stat(count))), position = position_stack(vjust = 0.5), color = accent_color, size = 5, fill = primary_color, label.padding = unit(0.25, "lines")) else NULL) + labs( title = title, x = x_title, y = y_title ) + # Customize x-axis labels (if (!is.null(x_labels)) scale_x_discrete(labels = x_labels) else NULL) + theme_minimal(base_size = 14) + theme( plot.title = element_text(size = 16, face = "bold", color = primary_color), axis.title = element_text(size = 12, color = primary_color), axis.text = element_text(size = 10, color = primary_color, angle = label_angle, hjust = 1), plot.margin = margin(10, 10, 10, 10), panel.grid.major = element_line(color = tertiary_color, linewidth = 0.2), panel.grid.minor = element_line(color = tertiary_color, linewidth = 0.1), panel.background = element_rect(fill = tertiary_color), axis.text.x = element_text(angle = label_angle, hjust = 1), axis.text.y = element_text(size = 10, color = primary_color) ) } ``` ## Day of Week The histogram presented below visualizes the number of survey submissions based on the day of the week. Each bar represents the frequency of submissions for a particular day, with the x-axis displaying the days (Monday through Sunday) and the y-axis showing the number of submissions for each corresponding day. This chart helps identify any trends in survey participation, such as whether submissions are more frequent at the beginning or end of the week. This could be valuable for understanding user behavior and improving survey timing or outreach strategies. ```{r create-histogram-day-of-week, echo=TRUE, message=FALSE, fig.height=6, fig.width=8} survey_data %>% mutate(DayOfWeek = factor(weekdays(CreationDate), levels = c("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"))) %>% create_histogram( survey_data, field = "DayOfWeek", title = "Submissions by Day of the Week", x_title = "Day", color_palette = c("#233f2b", "#7e9084", "#d9e1dd", "#face00")) ``` ```{r func-plot_submission_trends, echo=TRUE} plot_submission_trends <- function(data, days_ago = 30, color_palette = c("#154973", "#457aa5", "#eff6fb", "#face00"), title = NULL, subtitle = NULL, x_title = "Submission Date", y_title = "Number of Submissions") { # Default title and subtitle if (is.null(title)) title <- "Survey Submission Trends by Date" if (is.null(subtitle)) subtitle <- paste("Tracking submissions for the last", days_ago, "days") # Calculate the start date (days_ago days before today) start_date <- Sys.Date() - days_ago # Filter the data based on the calculated start date (up to today) submission_trends <- data %>% filter(CreationDate >= start_date) %>% group_by(CreationDate) %>% summarize(submissions = n()) # Create the plot with the new theming ggplot(submission_trends, aes(x = CreationDate, y = submissions)) + geom_line(color = color_palette[1], linewidth = 1) + # Line color from palette geom_point(color = color_palette[1], size = 3, shape = 16) + # Points for visibility labs( title = title, subtitle = subtitle, x = x_title, y = y_title ) + theme_minimal(base_size = 14) + theme( plot.title = element_text(hjust = 0.5, face = "bold", size = 16, color = color_palette[1]), plot.subtitle = element_text(hjust = 0.5, size = 12, color = "grey40"), axis.title.x = element_text(color = color_palette[1], size = 12), axis.title.y = element_text(color = color_palette[1], size = 12), axis.text = element_text(color = color_palette[1], size = 10), panel.grid.major = element_line(color = color_palette[3], linewidth = 0.2), panel.grid.minor = element_line(color = color_palette[3], linewidth = 0.1), panel.background = element_rect(fill = color_palette[3]), axis.text.x = element_text(angle = 45, hjust = 1), axis.text.y = element_text(size = 10, color = color_palette[1]) ) + # Add a smoothed trend line (loess) geom_smooth(method = "loess", color = color_palette[4], linewidth = 1, linetype = "dashed") } ``` ## 30 Day Trend The plot below visualizes the survey submission trends for the past 30 days. It shows the number of submissions made each day, highlighting variations over the last month. This type of plot is helpful for understanding trends in user activity, such as identifying peak submission days, periods of low activity, or gradual changes over time. The data used for this plot is filtered to include only submissions made in the last 30 days, with the submission count for each date represented by both the line and the points on the graph. A smoothed trend line (dashed) has been added to help visualize the overall submission pattern over this period. ```{r plot-submission-trends-30d, echo=TRUE, message=FALSE, fig.height=6, fig.width=8} survey_data$CreationDate <- as.Date(survey_data$CreationDate) plot_submission_trends(survey_data, days_ago = 30, color_palette <- c( "#233f2b", # primary "#7e9084", # secondary "#d9e1dd", # tertiary "#face00" # accent )) ``` ## 90 Day Trend The plot below visualizes the survey submission trends for the past 90 days. It shows the number of submissions made each day, highlighting variations over the last month. This type of plot is helpful for understanding trends in user activity, such as identifying peak submission days, periods of low activity, or gradual changes over time. The data used for this plot is filtered to include only submissions made in the last 90 days, with the submission count for each date represented by both the line and the points on the graph. A smoothed trend line (dashed) has been added to help visualize the overall submission pattern over this period. ```{r plot-submission-trends-90d, echo=TRUE, message=FALSE, fig.height=6, fig.width=8} survey_data$CreationDate <- as.Date(survey_data$CreationDate) plot_submission_trends(survey_data, days_ago = 90, color_palette <- c( "#233f2b", # primary "#7e9084", # secondary "#d9e1dd", # tertiary "#face00" # accent )) ``` ## Optional Question Response Rates ```{r func-calculate_response_rates, echo=TRUE, message=FALSE} # Function to calculate response rates for selected fields calculate_response_rates <- function(survey_data, fields, caption) { # Calculate the response rate for each field response_rates <- sapply(fields, function(field) { if (field == "Total Number of Species Planted") { # For "Total Number of Species Planted", consider answered if value is greater than 0 sum(survey_data[[field]] > 0, na.rm = TRUE) / nrow(survey_data) * 100 } else { # For other fields, check for non-NA values sum(!is.na(survey_data[[field]])) / nrow(survey_data) * 100 } }) # Round the response rates to 2 decimal places response_rates_rounded <- round(response_rates, 2) # Sort the response rates in descending order (highest to lowest) sorted_response_rates <- sort(response_rates_rounded, decreasing = TRUE) # Create a clean data frame with the field names and their response rates response_rate_table <- data.frame( "Field" = names(sorted_response_rates), "Response Rate (%)" = sorted_response_rates, stringsAsFactors = FALSE # Ensure the "Field" column is treated as character, not factor ) # Remove the row names (the extra column that appears as a result of conversion) rownames(response_rate_table) <- NULL # Fix column names to ensure proper headers colnames(response_rate_table) <- c("Field", "Response Rate (%)") # Display the table using kable for better formatting library(knitr) kable(response_rate_table, caption = caption, align = "l") } ``` The table below summarizes the response rates for optional top-level questions in the survey. These are the questions that all participants are asked, with some triggering additional follow-up questions based on responses. The response rate is the percentage of participants who provided an answer for each question. The "Total Number of Species Planted" question has special handling—only responses greater than 0 are considered valid, whereas for other questions, any non-NA value counts as a response. ```{r response-rate-table-optional, echo=TRUE, message=FALSE, fig.height=6, fig.width=8} fields <- c("Planter Contact Email (Optional)", "Funding Source (Optional)", "Land Ownership (Optional)", "Tree Size Planted (Optional)", "Source of Trees (Optional)", "Total Number of Species Planted") calculate_response_rates(survey_data, fields, "Response Rates for Key Survey Questions") ``` The following provides additional context for each survey question/field, detailing what the percentage represents. - **Planter Contact Email**: The percentage of respondents who provided their email address. - **Funding Source**: The percentage of respondents who identified their funding source. - **Land Ownership**: The percentage of respondents who indicated their land ownership status. - **Tree Size Planted**: The percentage of respondents who specified the size of trees they planted. - **Source of Trees**: The percentage of respondents who reported the source of the trees they planted. - **Total Number of Species Planted** : The percentage of respondents who provided the species of tree(s) they planted. # Participant Analysis {.tabset} [Back to Top](#) The following section contains an analysis of tree planting by participant type. ## Submissions The following plot shows the distribution of survey submissions based on participant type. This breakdown highlights the contributions of each participant group to the tree planting initiative. ```{r create-histogram-participant-type, echo=TRUE, message=FALSE, fig.height=6, fig.width=8} create_histogram( survey_data, field = "Who Planted The Tree(s)? (Required)", x_labels = c( "agency" = "State Agency", "community" = "Community Organization", "landowner" = "Private Landowner", "municipality" = "Municipal Government", "professional" = "Paid Professional" ), title = "Tree Planting Submissions by Participant Type", x_title = "Participant Type", color_palette = c("#233f2b", "#7e9084", "#d9e1dd", "#face00")) ``` ## Trees Planted This plot visualizes the total number of trees planted by each participant type, helping to evaluate the overall impact of different groups in the tree planting program. ```{r func-create_bar_chart, echo=TRUE, message=FALSE} create_bar_chart <- function(data, field, sum_field = NULL, x_labels = NULL, color_palette = c("#154973", "#457aa5", "#eff6fb", "#face00"), title = NULL, x_title = NULL, y_title = "Sum", max_label_count = 10, label_angle = 45, show_labels = TRUE) { # Default color palette primary_color <- color_palette[1] secondary_color <- color_palette[2] tertiary_color <- color_palette[3] accent_color <- color_palette[4] # Set default labels if not provided if (is.null(title)) title <- paste("Sum of", field) if (is.null(x_title)) x_title <- field # If no sum_field is provided, use counts as the default bar height if (is.null(sum_field)) { sum_field <- field data <- data.frame(!!field := data[[field]], Count = 1) } else { data <- data %>% group_by(.data[[field]]) %>% summarize(Sum = sum(.data[[sum_field]], na.rm = TRUE)) %>% ungroup() } # Plot ggplot(data, aes(x = .data[[field]], y = .data$Sum)) + geom_bar(stat = "identity", fill = primary_color, color = secondary_color) + # Add text labels with background and border (if (show_labels) geom_label(aes(label = scales::comma(Sum)), position = position_stack(vjust = 0.5), color = accent_color, size = 5, fill = primary_color, label.padding = unit(0.25, "lines")) else NULL) + labs( title = title, x = x_title, y = y_title ) + # Customize x-axis labels (if (!is.null(x_labels)) scale_x_discrete(labels = x_labels) else NULL) + theme_minimal(base_size = 14) + theme( plot.title = element_text(size = 16, face = "bold", color = primary_color), axis.title = element_text(size = 12, color = primary_color), axis.text = element_text(size = 10, color = primary_color, angle = label_angle, hjust = 1), plot.margin = margin(10, 10, 10, 10), panel.grid.major = element_line(color = tertiary_color, linewidth = 0.2), panel.grid.minor = element_line(color = tertiary_color, linewidth = 0.1), panel.background = element_rect(fill = tertiary_color), axis.text.x = element_text(angle = label_angle, hjust = 1), axis.text.y = element_text(size = 10, color = primary_color) ) } ``` ```{r create_bar_chart-participant-total-trees,echo=TRUE, message=FALSE, fig.height=6, fig.width=8} create_bar_chart( survey_data, field = "Who Planted The Tree(s)? (Required)", x_labels = c( "agency" = "State Agency", "community" = "Community Organization", "landowner" = "Private Landowner", "municipality" = "Municipal Government", "professional" = "Paid Professional" ), sum_field = "Number of Trees Planted (Required)", x_title = "Participant Type", y_title = "Total Trees Planted", title = "Total Trees Planted by Participant Type", color_palette = c("#233f2b", "#7e9084", "#d9e1dd", "#face00")) ``` ```{r func-create_summary_table, echo=TRUE} create_summary_table <- function(data, field, sum_field, remove_na = TRUE, table_font_size = 14) { # Input validation if (!field %in% colnames(data)) { stop(paste("Error: Field", field, "does not exist in the data")) } if (!sum_field %in% colnames(data)) { stop(paste("Error: Sum field", sum_field, "does not exist in the data")) } # Check if sum_field is numeric if (!is.numeric(data[[sum_field]]) && !is.integer(data[[sum_field]])) { stop(paste("Error: Sum field", sum_field, "is not numeric")) } # Summarize the data based on the field and sum_field provided summary_data <- data %>% group_by(!!sym(field)) %>% # Dynamically use the provided field name summarise( submissions = n(), # Count of submissions total_value = sum(!!sym(sum_field), na.rm = remove_na) # Sum of the specified field ) %>% mutate( submissions_percentage = submissions / sum(submissions) * 100, # Proportion of submissions value_percentage = total_value / sum(total_value) * 100 # Proportion of summed field ) # Format the table to display commas for the totals and round percentages summary_data_formatted <- summary_data %>% mutate( submissions = scales::comma(submissions), total_value = scales::comma(total_value), submissions_percentage = paste0(round(submissions_percentage, 1), "%"), value_percentage = paste0(round(value_percentage, 1), "%") ) # Create and style the table with customizable font size and other options summary_data_formatted %>% knitr::kable( col.names = c(field, "Number of Submissions", paste("Total", sum_field), "Proportion of Submissions (%)", "Proportion of Sum Field (%)"), caption = paste("Summary of Submissions and", sum_field, "by", field), align = c("l", "c", "c", "c", "c") ) %>% kableExtra::kable_styling( full_width = F, position = "center", bootstrap_options = c("striped", "hover"), font_size = table_font_size ) %>% kableExtra::column_spec(1, width = "20em", bold = TRUE) %>% # First column bold and wider kableExtra::column_spec(2, width = "12em") %>% # Submissions column kableExtra::column_spec(3, width = "12em") %>% # Total value column kableExtra::add_footnote("The proportions represent the percentage of submissions and sum of the field for each category relative to the overall dataset.") } ``` The following table provides a breakdown of the total number of trees planted by participant type. It shows both the total number of trees planted by each group and their proportional contribution to the overall planting efforts. This information helps assess which participant types have contributed the most to the tree planting program. ```{r participant-type-table, echo=TRUE, message=FALSE, fig.height=6, fig.width=8} survey_data %>% mutate( `Who Planted The Tree(s)? (Required)` = recode(`Who Planted The Tree(s)? (Required)`, "agency" = "State Agency", "community" = "Community Organization", "landowner" = "Private Landowner", "municipality" = "Municipal Government", "professional" = "Paid Professional") ) %>% create_summary_table("Who Planted The Tree(s)? (Required)", "Number of Trees Planted (Required)", remove_na = FALSE, table_font_size = 16) ``` ## Named User Activity ```{r named-user-activity-table, echo=TRUE, message=FALSE, fig.height=6, fig.width=8} survey_data %>% mutate(Creator = ifelse(is.na(Creator), "Public User", Creator)) %>% create_summary_table("Creator", "Number of Trees Planted (Required)", remove_na = FALSE, table_font_size = 16) ``` ## Unique E-mail Activity ```{r unique-email-activity-table, echo=TRUE, message=FALSE, fig.height=6, fig.width=8} survey_data %>% mutate(Creator = ifelse(is.na(`Planter Contact Email (Optional)`), "Not Provided", `Planter Contact Email (Optional)`)) %>% create_summary_table("Planter Contact Email (Optional)", "Number of Trees Planted (Required)", remove_na = FALSE, table_font_size = 16) ``` ## Municipal Activity ```{r} survey_data %>% mutate(`Participant Municipality (Optional)` = case_when( str_starts(`Participant Municipality (Optional)`, "c_") ~ str_replace(`Participant Municipality (Optional)`, "^c_", "") %>% paste0(" (city)"), str_starts(`Participant Municipality (Optional)`, "v_") ~ str_replace(`Participant Municipality (Optional)`, "^v_", "") %>% paste0(" (village)"), str_starts(`Participant Municipality (Optional)`, "t_") ~ str_replace(`Participant Municipality (Optional)`, "^t_", "") %>% paste0(" (town)"), TRUE ~ `Participant Municipality (Optional)` )) %>% create_summary_table("Participant Municipality (Optional)", "Number of Trees Planted (Required)", remove_na = FALSE, table_font_size = 16) ``` ## Organizaiton Activity # Location Analysis {.tabset} ```{r func-plot_geographic_data, echo=TRUE} plot_geographic_data <- function(joined_data, title, legend, fill_option = "plasma", subtitle = NULL, theme_options = theme_minimal(), legend_position = "right", color_scale = "viridis", save_path = NULL, na_fill_color = "lightgrey") { current_date <- format(Sys.Date(), "%B %d, %Y") # If subtitle is not provided, use the current date as subtitle subtitle_text <- ifelse(is.null(subtitle), paste("Date:", current_date), subtitle) # Handle missing data by filling with a specified color joined_data[is.na(joined_data$total_trees), "total_trees"] <- NA # Select the color scale based on the user's input if (color_scale == "viridis") { fill_color <- scale_fill_viridis_c(option = fill_option, na.value = na_fill_color) # Use na.value to fill NA } else if (color_scale == "RColorBrewer") { fill_color <- scale_fill_brewer(palette = "Set3") # Default RColorBrewer palette } else { fill_color <- scale_fill_manual(values = color_scale) # Custom color scale } # Create the plot plot <- ggplot(data = joined_data) + geom_sf(aes(fill = total_trees), color = "white") + fill_color + # Color scale for the plot theme_options + # Apply custom theme labs(title = title, subtitle = subtitle_text, # Subtitle is handled here fill = legend) + theme(axis.text = element_blank(), axis.title = element_blank(), legend.position = legend_position) # If save_path is provided, save the plot to file if (!is.null(save_path)) { ggsave(save_path, plot = plot, width = 10, height = 6) } # Return the plot return(plot) } ``` [Back to Top](#) ## By Region This map displays the **total number of trees planted** across each economic region in **New York State**. The counties are color-coded, with darker shades representing areas where more trees have been planted. This allows users to quickly see which counties have had the most extensive tree planting efforts. - **What to look for**: - **Dark colors**: Indicate regions with a higher number of trees planted. - **Lighter colors**: Represent regions with fewer trees planted. The map provides a visual overview of tree planting distribution across New York, making it easier to identify areas with the highest impact or need for further action. ```{r create-region-choropleth-map, echo=TRUE, message=FALSE, fig.height=6, fig.width=8} survey_data_aggregated <- survey_data %>% group_by(Region) %>% summarise(total_trees = sum(`Number of Trees Planted (Required)`, na.rm = TRUE)) shapefile_path <- "/home/nick/gitea/tree-tracker-report/data/redc/redc.shp" geographic_data <- st_read(shapefile_path) %>% mutate( REDC = str_replace(REDC, "Western NY", "Western New York"), REDC = str_replace(REDC, "Central NY", "Central New York"), REDC = str_replace(REDC, "Mid-Hudson", "Hudson Valley"), REDC = str_replace(REDC, "Capital Region", "Capital District"), ) %>% st_as_sf() survey_data_joined <- geographic_data %>% left_join(survey_data_aggregated, by = c("REDC" = "Region")) plot_geographic_data(joined_data = survey_data_joined, title = "Number of Trees Planted by Region in New York", legend = "Total Trees Planted", fill_option = "plasma", subtitle = "Generated: March 13, 2025", theme_options = theme_minimal(), legend_position = "right", color_scale = "viridis", na_fill_color = "lightgrey") ``` ```{r create-summary-table-region, echo=TRUE, message=FALSE, fig.height=6, fig.width=8} create_summary_table(survey_data, "Region", "Number of Trees Planted (Required)", remove_na = FALSE, table_font_size = 16) ``` ## By County This map displays the **total number of trees planted** across each county in **New York State**. The counties are color-coded, with darker shades representing areas where more trees have been planted. This allows users to quickly see which counties have had the most extensive tree planting efforts. - **What to look for**: - **Dark colors**: Indicate counties with a higher number of trees planted. - **Lighter colors**: Represent counties with fewer trees planted. The map provides a visual overview of tree planting distribution across New York, making it easier to identify areas with the highest impact or need for further action. ```{r create-county-choropleth-map, echo=TRUE, message=FALSE, fig.height=6, fig.width=8} survey_data_aggregated <- survey_data %>% group_by(County) %>% summarise(total_trees = sum(`Number of Trees Planted (Required)`, na.rm = TRUE)) geographic_data <- counties(state = "NY", cb = TRUE, progress = FALSE) %>% st_as_sf() %>% mutate(NAME = str_replace(NAME, "\\.", "")) # Remove period from "St. Lawrence" survey_data_joined <- geographic_data %>% left_join(survey_data_aggregated, by = c("NAME" = "County")) # Example of calling the function with enhancements plot_geographic_data(joined_data = survey_data_joined, title = "Number of Trees Planted by County in New York", legend = "Total Trees Planted", fill_option = "plasma", subtitle = "Generated: March 13, 2025", theme_options = theme_minimal(), legend_position = "right", color_scale = "viridis", # Default viridis scale na_fill_color = "lightgrey") # Color for NA values ``` ```{r create-summary-table-county, echo=TRUE, message=FALSE, , fig.height=6, fig.width=8} create_summary_table(survey_data, "County", "Number of Trees Planted (Required)", remove_na = FALSE, table_font_size = 16) ``` # Tree Analysis {.tabset} [Back to Top](#) ```{r func-create_species_summary_table, echo=TRUE} create_species_summary_table <- function(data, field, field_label = NULL) { # Replace empty strings and NA values with "Not Provided" before summarization data <- data %>% mutate( !!sym(field) := ifelse(!!sym(field) == "" | is.na(!!sym(field)), "Not Provided", !!sym(field)) # Replace empty strings and NAs ) # Clean up the species names: replace underscores with spaces and convert to title case data <- data %>% mutate( !!sym(field) := gsub("_", " ", !!sym(field)), # Replace underscores with spaces !!sym(field) := tools::toTitleCase(!!sym(field)) # Convert to title case ) # Summarize the data based on the field (e.g., Generic.Species.of.Tree) summary_data <- data %>% group_by(!!sym(field)) %>% summarise( submissions = n(), # Count of surveys for each species (or category) .groups = "drop" # To prevent issues with group structure ) %>% mutate( submissions_percentage = submissions / sum(submissions) * 100 # Proportion of surveys for each category ) # Format the table for display summary_data_formatted <- summary_data %>% mutate( submissions = scales::comma(submissions), # Format the submission counts with commas submissions_percentage = paste0(round(submissions_percentage, 1), "%") # Round percentage and append '%' ) # Determine the label for the field label <- ifelse(is.null(field_label), field, field_label) # Create and style the table summary_data_formatted %>% knitr::kable(col.names = c(label, "Number of Surveys", "Proportion of Surveys (%)"), caption = paste("Summary of Surveys by", label), align = c("l", "c", "c")) %>% # Align the columns (left for the field, center for others) kableExtra::kable_styling( full_width = F, position = "center", bootstrap_options = c("striped", "hover"), font_size = 14 ) %>% kableExtra::column_spec(1, width = "20em", bold = TRUE) %>% # First column (Species) bold and wider kableExtra::column_spec(2, width = "12em") %>% # Number of Surveys column kableExtra::column_spec(3, width = "12em") %>% # Proportion column kableExtra::add_footnote("The proportions represent the percentage of surveys for each species relative to the total surveys.") } ``` ## By Genus The following table shows a breakdown of survey submissions by **Genus**. For each genus, the table provides: 1. **Number of Surveys**: The total number of surveys where this genus was reported. 2. **Proportion of Surveys (%)**: The percentage of total surveys that reported this genus, relative to the entire dataset. 3. **"Not Provided" Category**: Any surveys that did not specify a genus are grouped under the "Not Provided" category. These figures provide an understanding of which genus are most commonly reported, how prevalent each genus is, and the proportion of surveys where no genus was specified. ```{r create-summary-table-genus, echo=TRUE, message=FALSE, fig.height=6, fig.width=8} create_species_summary_table(species_planted, "Generic Type of Tree (Optional)", "Tree Genus") ``` ## By Species The following table shows a breakdown of survey submissions by **Species**. For each species, the table provides: 1. **Number of Surveys**: The total number of surveys where this species was reported. 2. **Proportion of Surveys (%)**: The percentage of total surveys that reported this species, relative to the entire dataset. 3. **"Not Provided" Category**: Any surveys that did not specify a species are grouped under the "Not Provided" category. These figures provide an understanding of which species are most commonly reported, how prevalent each species is, and the proportion of surveys where no genus was specified. ```{r create-summary-table-species, echo=TRUE, message=FALSE, fig.height=6, fig.width=8} create_species_summary_table(species_planted, "Tree Species (Optional)", "Tree Species") ``` # Disadvantaged Communities {.tabset} ## By Region ```{r create-summary-table-region-dac, echo=TRUE, message=FALSE, , fig.height=6, fig.width=8} survey_data %>% filter(!is.na(`Disadvantaged Communities Indicator`), na.rm = TRUE) %>% create_summary_table("Region", "Number of Trees Planted (Required)", remove_na = FALSE, table_font_size = 16) ``` ## By County ```{r create-summary-table-county-dac, echo=TRUE, message=FALSE, , fig.height=6, fig.width=8} survey_data %>% filter(!is.na(`Disadvantaged Communities Indicator`), na.rm = TRUE) %>% create_summary_table("County", "Number of Trees Planted (Required)", remove_na = FALSE, table_font_size = 16) ``` ## By Municipality ```{r create-summary-table-county-municipality, echo=TRUE, message=FALSE, , fig.height=6, fig.width=8} survey_data %>% filter(!is.na(`Disadvantaged Communities Indicator`), na.rm = TRUE) %>% create_summary_table("Municipality", "Number of Trees Planted (Required)", remove_na = FALSE, table_font_size = 16) ```