<jupyter_start><jupyter_text>Sources  * https://medium.com/@traffordDataLab/lets-make-a-map-in-r-7bd1d9366098  * https://stackoverflow.com/questions/50859765/chloropleth-map-with-geojson-and-ggplot2  * https://www.r-graph-gallery.com/327-chloropleth-map-from-geojson-with-ggplot2.html<jupyter_code>library(sf)
library(ggplot2)
library(dplyr)
library(viridis)
library(tidyr)
library(gghighlight)
library(plotly)
library(tidyverse)
# Load map data
cp_map <- st_read("../data/central_park_geo.geojson", quiet = TRUE)
# Update values for different zones of CP West
cp_map$location <- as.character(cp_map$location)
cp_map$sitename <- as.character(cp_map$sitename)
cp_map$sitename[cp_map$location == 'CPW, W 97 St, West Drive, W 100 St'] <- 'Central Park West (Zone 1)'
cp_map$sitename[cp_map$location == 'CPW, 85 St Transverse, West Drive To 96 St'] <- 'Central Park West (Zone 2)'
cp_map$sitename[cp_map$location == 'West Drive, CPW, 65 St Transverse'] <- 'Central Park West (Zone 3)'
cp_map$sitename[cp_map$location == '66 St To 72 St, CPW To West Drive'] <- 'Central Park West (Zone 4)'

# Add numbers for each zone to display on map 

# Read in squirrel data
squirrel_data <- read.csv('../data/squirrel_data.csv')
# Filter data for counts about 5 squirrels
gt_5_sq <- squirrel_data %>% select(sitename, Unique_Squirrel_ID) %>% filter(Unique_Squirrel_ID > 5) %>% pull(sitename)
# Find center of each polygon to plot region number
centroids_filtered <- cp_map %>%
    filter((sitename %in% gt_5_sq)) %>%
    st_centroid() %>% 
    bind_cols(as_data_frame(st_coordinates(.))) %>%
    # Add column for number to plot on choropleth
    mutate(number = seq(1:40))
#Join map boundaries to squirrel data
data_map <- left_join(cp_map %>% filter(sitename %in% gt_5_sq), squirrel_data, by = 'sitename')
# Add column with umber that corresponds to number in centroids_filtered
data_map$number <- seq(1:nrow(data_map))
# Change colname for behaviors
colnames(data_map) <- c('propname',
'us_congres',
'zipcode',
'acres',
'location',
'gispropnum',
'retired',
'subcategor',
'communityb',
'department',
'precinct',
'retireddat',
'omppropid',
'nys_assemb',
'sitename',
'nys_senate',
'councildis',
'borough',
'descriptio',
'X',
'Unique_Squirrel_ID',
'Climbing',
'Approaching_humans',
'Vocalizing',
'Running_or_chasing',
'Eating_or_foraging',
'Count_diff',
'geometry',
'number')
# Add column to plot color difference
data_map <- data_map %>% 
    mutate(am_pm = case_when(Count_diff < 0 ~ "Higher count in PM", 
                            TRUE ~ "Higher count in AM"))
# Font size variables for below plots
ys = 14
xs = 14
ts = 24
#' Plots a choropleth of central park filled with color
#' according to count of squirrels. 
#'
#' @param highlight (optional) a character vector of sitenames to highlight
#'
#' @return ggplot chart
#'
#' @examples
#' plot_choropleth(c('<NAME>', 'The Ramble'))
plot_choropleth <- function(highlight = vector()) {
    full_map <- ggplot(data_map) + 
        geom_sf(aes(fill = Unique_Squirrel_ID), color = 'lightgrey') + 
        geom_text(aes(X, Y, label = number), 
                  data = centroids_filtered, 
                  size = 3, 
                  color = 'black') +        
        scale_fill_gradient(low = 'white', high = 'darkgreen', 
                            limits = c(0,max(squirrel_data$Unique_Squirrel_ID)),
                            name = 'Count') +
        labs(title = 'Central Park Squirrel Distribution', x = '', y = '') +
        theme_minimal() +
        theme(legend.position = c(0.8, 0.2), 
        plot.title = element_text(hjust = 0.5, size = ts), 
        axis.text.x = element_text(angle = 90, hjust = 1, size = xs),
        axis.text.y = element_text(size = ys))
    if (length(highlight) == 0) {
        ggplotly(full_map)
    } else {
        m_h <- full_map + 
        gghighlight(sitename %in% highlight, 
                    label_key = Unique_Squirrel_ID)
        ggplotly(m_h)
    }
}
#' Plots a bar chart of squirrel count by park region
#'
#' @param highlight (optional) a character vector of sitenames to highlight
#'
#' @return ggplot chart
#'
#' @examples
#' plot_counts_bar(c('<NAME>', 'The Ramble'))
plot_counts_bar <- function(highlight = vector()) {
    counts_full <- ggplot(data_map) + 
            geom_bar(aes(x = reorder(sitename, Unique_Squirrel_ID), 
                         y = Unique_Squirrel_ID, 
                         fill = Unique_Squirrel_ID, text = paste("Area name:", sitename, '<br>',"Squirrel count:", Unique_Squirrel_ID)), 
                     stat = 'identity') + 

            coord_flip() +
            scale_fill_gradient(low = 'white', 
                                high = 'darkgreen', 
                                limits = c(0,max(squirrel_data$Unique_Squirrel_ID)),
                                name = 'Count') +
            labs(title = 'Squirrel Distribution by Park Region', y = 'Squirrel Count', x = '', size = xs) +
            theme_minimal() +
            theme(panel.grid.major.y = element_blank(), 
            legend.position = c(0.8, 0.2), 
            plot.title = element_text(hjust = 0.5, size = ts), 
            axis.text = element_text(hjust = 1, size = xs),
            axis.title = element_text(size = ys))
    if (length(highlight) == 0) {
        ggplotly(counts_full, tooltip="text")
        } else {
            c_h <- counts_full +
                 gghighlight(sitename %in% highlight, 
                             label_key = Unique_Squirrel_ID)
            ggplotly(c_h,tooltip=c("x","y"))
    }
}
#' Plots a bar chart of squirrel behavior by park region
#'
#' @param highlight (default = empty) a character vector of sitenames to highlight
#' @param behavior (default = Running_or_chasing) column of behavior to plot with options
#'       Running_or_chasing, Eating_or_foraging, Vocalizing, Approaching_humans, Climbing
#'
#' @return ggplot chart
#'
#' @examples
#' plot_behaviors_bar(c('Ross Pinetum', 'The Ramble'))
plot_behaviors_bar <- function(behavior = 'Running_or_chasing', highlight = vector()) {
    b_bar <- ggplot(data_map) + 
        geom_bar(aes(reorder(sitename, !!sym(behavior)), !!sym(behavior),text = paste("Area name:", sitename, '<br>',"Squirrel count:", !!sym(behavior))),
                     stat = 'identity') + 
        coord_flip() +
        labs(title = paste('Count of Squirrels',
                           str_replace_all(behavior,'_',' '),
                           ' by Park Region'), 
             y = 'Squirrel Count', x = '') +
        theme_minimal() +
        theme(panel.grid.major.y = element_blank(), 
            plot.title = element_text(hjust = 0.5, size = ts), 
            axis.text = element_text(hjust = 1, size = xs),
            axis.title = element_text(size = ys))
    if (length(highlight) == 0) {
        ggplotly(b_bar, tooltip="text")
    } else {
        b_h <- b_bar + gghighlight(sitename %in% highlight, 
            label_key = Unique_Squirrel_ID)
        ggplotly(b_h,tooltip=c("x","y"))
    }
}

# Use a function make_graph() to create the graph

#' Plots a bar chart of change in squirrel count from AM to PM
#'    by park region
#'
#' @param highlight (optional) a character vector of sitenames to highlight
#'
#' @return ggplot chart
#'
#' @examples
#' plot_diff_bar(c('Ross Pinetum', 'The Ramble'))
plot_diff_bar <- function(highlight = list()) {
    if (length(highlight) == 0){
      diff_bar <- ggplot(data_map,
               aes(x = reorder(sitename, -Count_diff), 
                   y = -Count_diff,
                   fill = am_pm, text = paste("Area name:", sitename, '<br>',"Count difference:", -Count_diff))) +
        geom_bar(stat = "identity")  +
        labs(title = 'Squirrel Abundance: Morning vs. Afternoon', 
             y = 'Difference in count', 
             x = '') +
        scale_y_continuous(breaks=seq(-20,50,10)) +
        coord_flip() +
        theme_minimal() +
        theme(panel.grid.major.y = element_blank(), 
              legend.position = c(0.8, 0.1), 
              plot.title = element_text(hjust = 0.5, size = ts), 
              axis.text = element_text(hjust = 1, size = xs),
              axis.title = element_text(size = ys),
              legend.title = element_blank()) 

      ggplotly(diff_bar, tooltip="text")
    } else {
        diff_bar <- ggplot(data_map,
               aes(x = reorder(sitename, -Count_diff), 
                   y = -Count_diff,
                   fill = am_pm)) +
        geom_bar(stat = "identity")  +
        labs(title = 'Squirrel Abundance: Morning vs. Afternoon', 
             y = 'Difference in count', 
             x = '') +
        scale_y_continuous(breaks=seq(-20,50,10)) +
        coord_flip() +
        theme_minimal() +
        theme(panel.grid.major.y = element_blank(), 
              legend.position = c(0.8, 0.1), 
              plot.title = element_text(hjust = 0.5, size = ts), 
              axis.text = element_text(hjust = 1, size = xs),
              axis.title = element_text(size = ys),
              legend.title = element_blank()) 

        db_h <- diff_bar + gghighlight(sitename %in% highlight, 
            label_key = Unique_Squirrel_ID)
        ggplotly(db_h, tooltip=c("x","y"))
    }

}<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.13542795232936078, 'fraction_numerical': 0.011917659804983749, 'mean_word_length': 2.6299646087298467, 'pattern_counts': {'":': 0, '<': 38, '<?xml version=': 0, '>': 20, 'https://': 3, 'lorem ipsum': 0, 'www.': 1, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '584450', 'license': 'MIT', 'n_tokens_mistral': 3285, 'n_tokens_neox': 2959, 'n_words': 697, 'path': 'scripts/plot_in_R.ipynb', 'repo_name': 'firasm/DSCI-532_group-203_Milestone3-4', 'size': '9242'}