library(galah)
## galah: version 2.0.2
## ℹ Default node set to ALA (ala.org.au).
## ℹ See all supported GBIF nodes with `show_all(atlases)`.
## ℹ To change nodes, use e.g. `galah_config(atlas = "GBIF")`.
## Attaching package: 'galah'
## 
## The following object is masked from 'package:stats':
## 
##     filter
# this id is the unique identifier of our targeted species

id <- "https://biodiversity.org.au/afd/taxa/a3e5376b-f9e6-4bdf-adae-1e7add9f5c29"

# use an email that has been registed with ALA

galah_config(email = "x36.zhao@hdr.qut.edu.au") #this email must have been registed with ALA
galah_config(directory = "./input_data")

# filter out the data you want

my_species_data <- galah_call() |> 
  galah_filter(lsid == id, year >= 2019) |>
  atlas_occurrences(mint_doi = TRUE)
## Request for 28610 occurrences placed in queue
## Current queue length: 1
## ----
## Downloading
attr(my_species_data, "doi")
## [1] "https://doi.org/10.26197/ala.9f634688-054a-4ce1-8be1-1ae1e45893b0"
#Generate citation
atlas_citation(my_species_data)
## Atlas of Living Australia (10 May 2024) Occurrence download https://doi.org/10.26197/ala.9f634688-054a-4ce1-8be1-1ae1e45893b0
## 
## Please consider citing R & galah, in addition to your dataset. To do so, call:
## citation()
## citation('galah')
my_species_data$Year <- as.numeric(substr(my_species_data$eventDate, 1,4)) # extract the year and make it as number

my_species_data <- my_species_data[-is.na(my_species_data$Year)]

my_species_data <- dplyr::rename(my_species_data, latitude = decimalLatitude, 
    longitude = decimalLongitude)  # change the name of long and lat to common names

Noise miner is a species that compete with Scarlet Robin

# this id is the unique identifier of our targeted species

id <- "https://biodiversity.org.au/afd/taxa/ee7498bf-c57c-4463-b313-710d4959cc95"

# use an email that has been registed with ALA

galah_config(email = "x36.zhao@hdr.qut.edu.au") #this email must have been registed with ALA
galah_config(directory = "./input_data")

# filter out the data you want

noiseminer_data <- galah_call() |> 
  galah_filter(lsid == id, year >= 2023) |>
  atlas_occurrences(mint_doi = TRUE)
## Request for 34319 occurrences placed in queue
## Current queue length: 1
## ----
## Downloading
attr(noiseminer_data, "doi")
## [1] "https://doi.org/10.26197/ala.120475b4-ebd6-4990-833b-323b9dad9e49"
#Generate citation
atlas_citation(noiseminer_data)
## Atlas of Living Australia (10 May 2024) Occurrence download https://doi.org/10.26197/ala.120475b4-ebd6-4990-833b-323b9dad9e49
## 
## Please consider citing R & galah, in addition to your dataset. To do so, call:
## citation()
## citation('galah')
noiseminer_data <- dplyr::rename(noiseminer_data, latitude = decimalLatitude, 
    longitude = decimalLongitude)

Pied Currawong is a major predator of Scarlet Robin

# this id is the unique identifier of our targeted species

id <- "https://biodiversity.org.au/afd/taxa/eb315a61-418b-4a12-bc98-9096fe17bde9"

# use an email that has been registed with ALA

galah_config(email = "x36.zhao@hdr.qut.edu.au") #this email must have been registed with ALA
galah_config(directory = "./input_data")

# filter out the data you want

PiedCurrawong_data <- galah_call() |> 
  galah_filter(lsid == id, year >= 2023) |>
  atlas_occurrences(mint_doi = TRUE)
## Request for 20279 occurrences placed in queue
## Current queue length: 1
## ----
## Downloading
attr(PiedCurrawong_data, "doi")
## [1] "https://doi.org/10.26197/ala.7d1ea23a-2b44-44ed-a854-1499593830d2"
#Generate citation
atlas_citation(PiedCurrawong_data)
## Atlas of Living Australia (10 May 2024) Occurrence download https://doi.org/10.26197/ala.7d1ea23a-2b44-44ed-a854-1499593830d2
## 
## Please consider citing R & galah, in addition to your dataset. To do so, call:
## citation()
## citation('galah')
PiedCurrawong_data <- dplyr::rename(PiedCurrawong_data, latitude = decimalLatitude, 
    longitude = decimalLongitude)

Preparation of Climate Data for the observations of Scarlet Robin

library(raster)
## Loading required package: sp
## 
## Attaching package: 'raster'
## The following object is masked from 'package:galah':
## 
##     select
library(geodata)
## Loading required package: terra
## terra 1.7.71
climatedata <- worldclim_country("AU", var="bio", res= 0.5, path = "./input_data") # Extract 19 Bioclimatic variables from www.worldclim.org for Australian wide with a resolution of 30 seconds.

my_species_data_location <- my_species_data[,c("longitude","latitude")] #Extract Scarlet Robin Occurences to a new list

my_species_data_location <- dplyr::rename(my_species_data_location, y = latitude, 
    x = longitude) #change the name of long and lat to common names

climatevalues <- extract(climatedata, my_species_data_location)  #Extrac bioclimatic variable values to Scarlet Robin Occurence data

ColNamesFull <- c("Annual Mean Temperature", "Mean Diurnal Range (Mean of monthly (max temp - min temp))", "Isothermality (BIO2/BIO7) (×100)", "Temperature Seasonality (standard deviation ×100)", "Max Temperature of Warmest Month", "Min Temperature of Coldest Month", "Temperature Annual Range (BIO5-BIO6)",
                  "Mean Temperature of Wettest Quarter", "Mean Temperature of Driest Quarter", "Mean Temperature of Warmest Quarter", "Mean Temperature of Coldest Quarter", "Annual Precipitation", "Precipitation of Wettest Month", "Precipitation of Driest Month", "Precipitation Seasonality (Coefficient of Variation)", "Precipitation of Wettest Quarter", "Precipitation of Driest Quarter", "Precipitation of Warmest Quarter", "Precipitation of Coldest Quarter") # The full name of 19 Bioclimatic variables for user to choose

Data visualisation

library(shiny)
library(leaflet)
library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:terra':
## 
##     intersect, union
## The following objects are masked from 'package:raster':
## 
##     intersect, select, union
## The following object is masked from 'package:galah':
## 
##     desc
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
library(RColorBrewer)
library(ggplot2)
library(data.table)
## 
## Attaching package: 'data.table'
## The following objects are masked from 'package:dplyr':
## 
##     between, first, last
## The following object is masked from 'package:terra':
## 
##     shift
## The following object is masked from 'package:raster':
## 
##     shift
library(bslib)
## 
## Attaching package: 'bslib'
## The following object is masked from 'package:utils':
## 
##     page
#data input

data <- my_species_data

# create the color palette

groups = unique(my_species_data$Year)
my_palette <- brewer.pal(length(groups), "Paired")
factpal <- colorFactor(my_palette, domain = groups, ordered = TRUE)

ui <- fluidPage(
  titlePanel("Map of Observations on Scarlet Robin in the Atlas of Living Australia"),
  
  fluidRow(
    column(4, 
      br(),
      h4("Scarlet Robin"),
      imageOutput("photo"),
      p("Photo by pen_ash on Unsplash"),
    ),
    
    column(8, 
        br(),
        tabsetPanel(type = "tabs",
        tabPanel("Map", leafletOutput("mymap")),
        tabPanel("Orginal Data", dataTableOutput("table"))),
        h4("Observations of Scarlet Robin from 2019 to 2024"),
    )
  ),
 
  fluidRow(
    style = 'margin-left: 1%; margin-right: 1%;',
    br(),
    h3("Two temperal trends"),
    br(),
    uiOutput("SR_output"),
    column(6, h3("Temperal trend of total observations"), br(), plotOutput("summary1")),
    column(6, h3("Temeral trend of data sources"),br(),plotOutput("summary2"))
    ),
  
  fluidRow(
    style = 'margin-left: 1%; margin-right: 1%;',
    br(),
    h3("Climatic Variables"),
    uiOutput("CV_output"),
    plotOutput("BIOslected"),
    
  ),
  

    fluidRow(
    style = 'margin-left: 1%; margin-right: 1%;',
    br(),
    h3("Threats to Scarlet Robin"),
    
    column(4, 
      br(),
      h4("1. Competition"),
      imageOutput("NoiseMiner"),
      p("Photo by Vlad Kutepov on Unsplash"),
    ),
    
    column(8, 
    br(),
    h4("Observations of Noise Miner"),
    leafletOutput("noiseminermap"),
    p("Observation of Noise Miner"),
    )
  ),
  
    fluidRow(
    style = 'margin-left: 1%; margin-right: 1%;',
    br(),
    
    column(4, 
      br(),
      h4("2. Predation"),
      imageOutput("PiedCurrawong"),
      p("Photo by Bird Canberra"),
    ),
    
    column(8, 
    br(),
    h4("Observations of Pied Currawong"),
    leafletOutput("piedcurrawongmap"),
    p("Observation of Pied Currawong"),
    )
  ),
  
        # Add About text
  fluidRow(
    style = 'margin-left: 1%; margin-right: 1%;',
    br(),
    h4("About"),
    p("This app provides an example of the visualisation of species occurrence data for Scarlet Robin from the ", a("Atlas of Living Australia.", href="https://www.ala.org.au/", target = "_blank")),
    p("The raw data can be accessed from the following DOI and please cite as: Atlas of Living Australia (9 May 2024) Occurrence download", a("https://doi.org/10.26197/ala.603b3333-ab00-4ef6-a24f-5f5811b1f719", href="https://doi.org/10.26197/ala.603b3333-ab00-4ef6-a24f-5f5811b1f719", target = "_blank"), ". The data was imported using", a("galah",href="https://support.ala.org.au/support/solutions/articles/6000261466-ala-s-r-package-galah"), "and the site was built in", a("RStudio", href="https://www.rstudio.com/", target = "_blank"), "with", a("Shiny.", href="https://www.rstudio.com/products/shiny/", target = "_blank"))
   ),
  
  )
## `shiny::dataTableOutput()` is deprecated as of shiny 1.8.1.
## Please use `DT::DTOutput()` instead.
## See <https://rstudio.github.io/DT/shiny.html> for more information.
server <- function(input, output) {
    output$SR_output <- renderUI({
        selectInput(inputId = "Year_input", "Year", sort(unique(data$Year)), 
            selected = "2019")
    })
    

    output$CV_output <- renderUI({
      selectInput(inputId ="climatevariable", "Climatic Variable", choices = ColNamesFull, 
                selected = "Annual Mean Temperature")
    })
    
    output$mymap <- renderLeaflet({
        leaflet(data) %>% addTiles() %>% addCircleMarkers(~longitude, ~latitude, 
            popup = data$Year, radius = 2, weight = 5, opacity = 0.5, fill = TRUE, 
            fillOpacity = 0.2,clusterOptions = markerClusterOptions())
    })
    
    output$noiseminermap <- renderLeaflet({
        leaflet(noiseminer_data) %>% addTiles() %>% addCircleMarkers(~longitude, ~latitude, 
            popup = data$Year, radius = 2, weight = 5, opacity = 0.5, fill = TRUE, 
            fillOpacity = 0.2)

    })
    
    output$piedcurrawongmap <- renderLeaflet({
        leaflet(PiedCurrawong_data) %>% addTiles() %>% addCircleMarkers(~longitude, ~latitude, 
            popup = data$Year, radius = 2, weight = 5, opacity = 0.5, fill = TRUE, 
            fillOpacity = 0.2)

    })

    # Add the photo of Scarlet Robin
    output$photo <- renderImage({
    list(
      src = "./input_data/pen_ash-g9jN7qMZ2l0-unsplash.jpg",
      contentType = "image/jpeg",
      width = 300,
      height = 400
    )
  }, deleteFile = FALSE)
    
    # Add the photo of Noise Miner
    output$NoiseMiner <- renderImage({
    list(
      src = "./input_data/vlad-kutepov-nDJvrv9a-FA-unsplash.jpg",
      contentType = "image/jpeg",
      width = 300,
      height = 400
    )
  }, deleteFile = FALSE)
    
    
    # Add the photo of Pied Currawong
    output$PiedCurrawong <- renderImage({
    list(
      src = "./input_data/piedcurrawong.jpg",
      contentType = "image/jpeg",
      width = 300,
      height = 400
    )
  }, deleteFile = FALSE)
    
    
    # Add the table
    
    output$table <- renderDataTable({
        table <- my_species_data
    })
    

    # Add summary plot counting species by occurrences.
    
    output$summary1 <- renderPlot({
            ggplot(data, aes(x=Year))+ geom_bar(show.legend = TRUE) + 
            labs(x = "Year of Observation", y = "Occurrences")+
        theme(axis.text.x = element_text(angle = 45, hjust = 1)) 
    })
    
    output$summary2 <- renderPlot({
       data %>% filter(data$Year %in% input$Year_input) %>% count(dataResourceName) %>% 
            ggplot(aes(x = reorder(dataResourceName, n), y = n, 
            fill = dataResourceName)) + geom_bar(stat = "identity", show.legend = FALSE) + 
            labs(x = "Data Resource", y = "Occurrences")+
        coord_flip()+
        theme(axis.text.x = element_text(angle = 60, hjust = 1)) 
    })
    
 output$BIOslected <- renderPlot({
        # Print debug information
        print("Debug Info:")
        print(paste("Selected Climate Variable:", input$climatevariable))
        print(paste("Column Names:", ColNamesFull))
        
        matching_index <- which(ColNamesFull == input$climatevariable) + 1
        
        # Print matching index for debug
        print(paste("Matching Index:", matching_index))
        
        if (length(matching_index) > 0 && matching_index <= ncol(climatevalues)) {
            selected_climate_values <- climatevalues[, matching_index]
            
            # Print the selected climate values for debug
            print(selected_climate_values)
            
            if (is.numeric(selected_climate_values)) {
                ggplot(data.frame(selected_climate_values), aes(x = selected_climate_values)) +
                    geom_histogram(aes(y = ..density..), colour = "black", fill = "white") +
                    geom_density(alpha = .2, fill = "#FF6666") +
                    labs(x = input$climatevariable, y = "Density")
            } else {
                ggplot() + 
                    annotate("text", x = 1, y = 1, label = "Selected climate variable is not numeric", size = 5, hjust = 0.5) + 
                    theme_void()
            }
        } else {
            ggplot() + 
                annotate("text", x = 1, y = 1, label = "Invalid climate variable selected", size = 5, hjust = 0.5) + 
                theme_void()
        }
    })
    
    # Add the download file details
    output$downloadData <- downloadHandler(filename = function() {
        paste("scarlet_robin", ".csv", sep = "")
    }, content = function(file) {
        file.copy("scarlet_robin.csv", file)
    }, contentType = "text/csv")
    
}

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