GY672-Assignment 2-Weather Station Dygraph

Author

Conor McKenna

Introduction

Rainfall is one of the key defining features of Ireland’s climate with a direct influence on the country’s agriculture and natural ecosystems. According to observed patterns from 1991-2020, Ireland’s mean precipitation per annum was 1208.43 mm (https://climateknowledgeportal.worldbank.org/), however precipitation can vary spatially and temporally.

Figure 1: Heavy Rainfall in Ireland
Figure 1: Heavy Rainfall in Ireland

In Ireland, the West of Ireland normally experiences higher precipitation levels due to geographic features like the proximity to the Atlantic Ocean and more upland regions producing relief rainfall. For example, according to Kiely (1999) monthly rainfall in the west in the winter is 150 mm and 50 mm in the summer. Temporal variation in rainfall is more obvious in the west across seasons as in the east mean rainfall is around 60 mm per month throughout the year. Rainfall is measured using rain gauges (Figure 2) or tipping buckets that tip water over after 0.1 or 0.2 mm of water falls into them, recording the number of tips (Figure 3)

Figure 2: Rain Gauge <https://www.met.ie/climate/what-we-measure/rainfall>
Figure 2: Rain Gauge https://www.met.ie/climate/what-we-measure/rainfall


Figure 3: Tipping Bucket <https://www.met.ie/climate/what-we-measure/rainfall>
Figure 3: Tipping Bucket https://www.met.ie/climate/what-we-measure/rainfall

Having an understanding of the rainfall patterns across months and years is essential for water resource management, agricultural planning, flood risk analysis and many more sectors of the economy and environment (Teagasc, 2024). This blog aims to discuss rainfall trends from data recorded at 4 spatially distinct weather stations in Ireland. By using interactive, visual aids like dygraphs we can analyse both spatial and temporal changes in rainfall across months and years in Ireland, to improve our understanding of Ireland’s climate and how rainfall has changed in recent years with regard to climate change.

Data Used

The rainfall data set was supplied by the GY672 module lecturer Christopher Brunsdon. The data set contained 49500 weather observations across 25 unique weather stations in Ireland, spanning 164 years from 1850 to 2014. Simple data exploration methods to understand the data set are included below. For most stations a monthly precipitation value in each year is contained. There are 4 columns in this dataset: Year, Month, Rainfall (mm) and Station. This data set needed to be filtered and prepared in advance of creating dygraphs.

Showing Number of Stations

Code
rain <- read.csv("rain.csv")

unique(rain$Station)
 [1] "Ardara"                    "Derry"                    
 [3] "Malin Head"                "Armagh"                   
 [5] "Belfast"                   "Strokestown"              
 [7] "Markree Castle"            "Drumsna"                  
 [9] "Birr"                      "Athboy"                   
[11] "University College Galway" "Cappoquinn"               
[13] "Mullingar"                 "Phoenix Park"             
[15] "Dublin Airport"            "Shannon Airport"          
[17] "Portlaw"                   "Foulksmills"              
[19] "Enniscorthy"               "Rathdrum"                 
[21] "Valentia"                  "Cork Airport"             
[23] "Killarney"                 "Roches Point"             
[25] "Waterford"                

Showing Year Range

Code
year_range<- range(rain$Year)
print(year_range)
[1] 1850 2014

The 4 weather stations in question for this analysis were Dublin Airport, Cork Airport, University College Galway and Belfast. By using these 4 spatially distinct stations with one in the north, south, east and west of the island of Ireland, the monthly analysis could look at differences in rainfall across space. The 4 weather stations are highlighted in the interactive map below (Figure 1).

Code
library(dplyr)
library(sf)
library(tmap)

# Define station coordinates
station_coords <- data.frame(
  Station = c("Cork Airport", "University College Galway", "Dublin Airport", "Belfast"),
  Latitude = c(51.8475, 53.2800, 53.4213, 54.6079),
  Longitude = c(-8.4971, -9.0624, -6.2701, -5.9264)
)

# Filter and prepare spatial object
fourstations <- station_coords %>%
  st_as_sf(coords = c("Longitude", "Latitude"), crs = 4326)

# Plot the interactive map with a basemap
tmap_mode("view")
tm_shape(fourstations) +
  tm_bubbles(size = 0.25, col = "red", popup.vars = c("Station")) +
  tm_basemap("OpenStreetMap") +
  tm_view(set.view = c(-8, 53, 6)) + 
  tm_layout(title = "Figure 4: Interactive Map with Selected Weather Stations")

Data Preparation

To create user-friendly, clear dygraphs to showcase monthly rainfall patterns across the 164 year period, the original was manipulated in several ways. A date column needed to be created, the specific stations needed to be filtered for while other data manipulation tools were required.

Creating a Date Column

In the original data set, the month and year of rainfall recordings were in separate columns. However to produce one of the types of dygraphs we want, we require to have a date column that combines these 2 columns. A new column called ‘Date’ was created with the format yyyy-mm-dd. As the data set contained no date column, each entry was assigned 01, for the date indicating the start of the month for consistency. To construct the date column, the mutate function in the dpylr package was used as seen in the code chunk below.

Code
raindate <- rain %>%
  mutate(
    Date = as.Date(paste(Year, Month, "01", sep = "-"), format = "%Y-%b-%d")
  )

head(raindate)
  Year Month Rainfall Station       Date
1 1850   Jan    169.0  Ardara 1850-01-01
2 1851   Jan    236.4  Ardara 1851-01-01
3 1852   Jan    249.7  Ardara 1852-01-01
4 1853   Jan    209.1  Ardara 1853-01-01
5 1854   Jan    188.5  Ardara 1854-01-01
6 1855   Jan     32.3  Ardara 1855-01-01

This new ‘Date’ column gives us a consistent time index which can be used in time series functions like dygraphs to understand rainfall fluctuations in our large data set.

Filtering for Four Specific Stations

As can be seen in the segment from the data set above, stations that we do not include in our analysis (21 of them) are still present. Therefore, to focus the analysis on only Dublin Airport, Cork Airport, University College Galway and Belfast weather stations, they need to be filtered for using the dpylr package.

Code
selected_stations <- c("Belfast", "Dublin Airport", "University College Galway","Cork Airport" )
rainfilter <- raindate %>%
  filter(Station %in% selected_stations)

unique(rainfilter$Station)
[1] "Belfast"                   "University College Galway"
[3] "Dublin Airport"            "Cork Airport"             

With this code, we created a vector (selected_stations), containing the 4 key weather stations. We then filtered for this vector from the data set formed in the previous step. The unique() function that was previously used now shows only the 4 important stations for the analysis.

Reshaping Data Frame into Wide Format

Initially, the data was in long format, with every row representing a different date at a different weather station. However to create dygraphs, we need this data in a wide format where each row contains a individual date, and then the 4 rainfall measurements from each of the weather stations. This data frame will therefore have a column for the date and then 4 columns, for one of each of the stations as seen below.

Code
library(tidyr)
rainwide <- rainfilter %>%
  select(Date, Station, Rainfall) %>%
  pivot_wider(names_from = Station, values_from=Rainfall)

# Increase the number of significant figures for tibble display
options(pillar.sigfig = 10)

# Print tibble 
head(rainwide)
# A tibble: 6 × 5
  Date       Belfast `University College Galway` `Dublin Airport` `Cork Airport`
  <date>       <dbl>                       <dbl>            <dbl>          <dbl>
1 1850-01-01   115.7                       108.9             75.8          155.3
2 1851-01-01   156.4                       163.8            112            359.5
3 1852-01-01   157.2                       174.9             80.3          216.2
4 1853-01-01   107.2                       152.8             74.7          191.3
5 1854-01-01   116.2                       133.1            101.1          157  
6 1855-01-01    16.1                        33.9             11.3            9.9

The pivot_wider() function in the tidyr package transformed each of the selected stations into its own column to enable time series examination. Now we can compare rainfall levels at the four different stations, along the same time scale to gain clearer insights to rainfall patterns.

Converting to a Time Series Object

Finally, the data frame (rainwide) needed to be transformed into an xts (extensible time series object) to allow later dygraph creation. The xts package needed to be installed for this part of the data preparation

Code
library(xts)
rain_xts <- xts(rainwide[,-1], order.by = rainwide$Date)
head(rain_xts)
           Belfast University College Galway Dublin Airport Cork Airport
1850-01-01   115.7                     108.9           75.8        155.3
1850-02-01   120.5                     131.5           47.8         92.6
1850-03-01    56.8                      56.6           18.5         56.0
1850-04-01   142.6                     120.5           97.5        207.2
1850-05-01    57.9                      69.8           58.6         35.3
1850-06-01    62.0                      74.7           43.6         11.4

The code rainwide [,-1] excluded the first column in ‘rainwide’ which was Date. Then the order.by = rainwide$Date segment used the Date column to order the values in the time series chronologically. The xts function then combined these two objects into an xts object where the rows represent dates and the columns represent rainfall values at stations. Now the date column is treated as a time index and not a standard column as seen before in the wide format data frame.

Dygraph Creation

Combined Stations Dygraph View

An interactive dygraph was generated to visualise the temporal and spatial rainfall trends across Ireland between 1850 to 2014. These interactive plots allow users to zoom in to specific time periods within the 164 years to compare all 4 stations directly. The dygraph was created with the xts object using the following code:

Code
library(dygraphs)

# Create dygraph
dygraph(rain_xts, main = "Monthly Rainfall at Selected Weather Stations") %>%
  dyRangeSelector() %>%
  dyAxis("y", label = "Rainfall (mm)") %>%
  dyOptions(colors = c("blue", "green", "orange", "purple")) %>%
  dyLegend(show = "always", hideOnMouseOut = FALSE) %>%
  dyOptions(gridLineColor = "lightgray")

Figure 5: Combined Dygraph


The first segment of the code using the dygraph package created the base graph using the xts object previously made dygraph(rain_xts). The main= function was used to choose a suitable title for our dygraph.

Adding the range selector seen below the dygraph allows us to manually focus on certain time periods by dragging the two ends of the range selector horizontally. Therefore we can look at rainfall on a broad scale between years and decades or focus in on monthly differences across years. Unique colours were applied to each weather station with the aim of using a colour-blind friendly palette. The function dyLegend() provides information on the time series, as when the user hovers their mouse over a specific time on the graph, it will provide the date and 4 rainfall measurements for the 4 stations. Finally, the hideOnMouseOut = FALSE function just ensures that the legend is still visible when the mouse is not over the graph, to improve readability.

Individual Dygraphs

Here we offer an alternative view of being able to see the four stations and their rainfall patterns on individual dygraphs. This helps offer a decluttered view across stations, which may be an issue in the original dygraph. Once again there is a range selector equipped at the bottom of the dygraphs that is attributed to all 4 stations, so when this selector is adjusted, all stations adjust to that time period accordingly. To construct this, the original xts was split into 4 individual xts objects.

Code
library(dygraphs)

# Assuming 'rain_xts' is the overall xts object
belfast_xts <- rain_xts[, "Belfast"]
dublin_xts <- rain_xts[, "Dublin Airport"]
galway_xts <- rain_xts[, "University College Galway"]
cork_xts <- rain_xts[, "Cork Airport"]


# Generate the dygraphs
htmltools::tagList(
  dygraph(belfast_xts, main = "Rainfall at Belfast", width = 800, height = 130, group = "rainfall_group"),
  dygraph(dublin_xts, main = "Rainfall at Dublin Airport", width = 800, height = 130, group = "rainfall_group"),
  dygraph(galway_xts, main = "Rainfall at University College Galway", width = 800, height = 130, group = "rainfall_group"),
  dygraph(cork_xts, main = "Rainfall at Cork Airport", width = 800, height = 170, group = "rainfall_group") %>%
    dyRangeSelector()
)

Figure 6: 4 Individual Dygraphs with shared Range Selector

Results & Observations

Our dygraphs displayed spatial and temporal patterns across four weather stations in Ireland with regard to rainfall, highlighting the influence of location and seasonal changes. From a general view and when sliding the range selector along the years, Cork Airport and University College Galway weather stations recorded most of the peaks in rainfall levels in summer and winter. On the other hand, Dublin Airport consistently had the lowest rainfall levels across the time period. The highest monthly rainfall recorded at one of these stations in the 164 year period was at Cork Airport in December 1899 (460.5 mm). The dygraph extract in figure 7 of 2012-2014 below highlights the stark difference in summer and winter rainfall levels in the west, with peaks in between October-January and lower rainfall emerging in the summer months.


Figure 7: Dygraph Extract from April 2012 to December 2014
Figure 7: Dygraph Extract from April 2012 to December 2014


Using the alternate view of individual dygraphs, we can notice these seasonal and monthly trends easier by separating the stations. Figure 8 below shows an extract of the data from November 1975 to July 1978. In this view, the seasonal variation in rainfall in the west (University College Galway) is immensely visible with a peak in rainfall in January 1976 followed by a low of 3.8 mm in August 1976. The other dygraphs also show how rain in the east is generally less variable with steady levels present between April 1977 and July 1978. One other trend noticed when swiping through the data with the range selector was that rainfall levels in Dublin Airport and Belfast seemed to mirror each other across many years, reflected in figure 8 below. This may occur due to the geographic proximity of these stations and because they are both on the eastern side of the island, further away from the Atlantic where rain is more plentiful. These interesting trends would not be as simple to visualise without the aid of these dygraphs created in R.


Figure 8: Dygraph Extract from April 1977 to July 1978
Figure 8: Dygraph Extract from April 1977 to July 1978


Conclusion

Rainfall is a vital feature in Ireland’s climate which affects its economic and environmental health while being open to wide-scale variation. Using interactive dygraphs to help comb through historical data, allowed us to identify patterns across four geographically distinct weather stations. These patterns which have been documented before are influenced by geographic location and seasonality, show the importance for understanding climate trends, especially when decision-making in agriculture or flood management is required. Dygraphs innate ability to provide interaction via features like the range selector make them an engaging, suitable tool for analysing historical data.

References