Code
library(rnoaa)
library(plotly)This tutorial shows how to download, clean, and visualize long-term weather data for any airport in the world using the NOAA Integrated Surface Database (ISD) — no FTP, no API key, no paid data.
The example uses Athens Eleftherios Venizelos (LGAV), but every step works for any ICAO station code.
Outputs:
| Plot | What it shows |
|---|---|
| Daily ribbon | Temperature range (min–max) for every day |
| Monthly ribbon | Smoothed monthly range with gradient line |
| Heatmap max | Monthly max temperature by year |
| Heatmap min | Monthly min temperature by year |
| Decomposition | Trend + seasonal + residual components |
NOAA ISD identifies stations by USAF and WBAN codes. The easiest way to find them is by ICAO airport code.
# A tibble: 92 × 6
station_name icao usaf wban lat lon
<chr> <chr> <chr> <chr> <dbl> <dbl>
1 ORESTIAS "" 166000 99999 41.8 26.5
2 SERRAI "" 166060 99999 41.1 23.6
3 KOMOTINI "" 166100 99999 41.1 25.4
4 FLORINA "" 166130 99999 40.8 21.4
5 ARISTOTELIS "LGKA" 166140 99999 40.4 21.3
6 EDESSA "" 166181 99999 40.8 22.0
7 SEDES(GAFB) "" 166200 99999 40.6 23.0
8 MAKEDONIA "LGTS" 166220 99999 40.5 23.0
9 MEGAS ALEXANDROS INTL "LGKV" 166240 99999 40.9 24.6
10 KAVALA/AMIGDHALEON "" 166250 99999 40.9 24.4
# ℹ 82 more rows
Change
"LGAV"to any ICAO code —"EGLL"for Heathrow,"KJFK"for New York, etc.
rnoaa::isd() replaces the old wget + FTP workflow. It downloads, decompresses, and parses the ISD binary format automatically. Each call fetches one year; a loop collects all years into a list.
years<-2001:2026
data_list<-list()
for(yr in years) {
tryCatch({
d<-rnoaa::isd(usaf=usaf,wban=wban,year=yr,progress=FALSE)
data_list[[as.character(yr)]]<-d
message(" downloaded ",yr," (",nrow(d)," rows)")
},error=function(e) message(" skip ",yr,": ",conditionMessage(e)))
}
# the years do not all have the same columns: give each year every column, NA where it has none
columns<-unique(unlist(lapply(data_list,names)))
data_list<-lapply(data_list,function(d) {
d<-as.data.frame(d)
d[setdiff(columns,names(d))]<-NA
d[columns]
})
df_raw<-do.call(rbind,data_list)
rownames(df_raw)<-NULL
message("Total rows: ",nrow(df_raw))Years where data are unavailable are silently skipped by
tryCatch. 2026 data may be partial depending on when you run this.
NOAA ISD encodes missing measurements as 9999 in the raw file. After dividing by 10 (ISD stores all values as tenths of the unit), missing temperature becomes 999.9°C — a physically impossible value that will corrupt any aggregate (mean, max, min) if not removed.
df_data<-df_raw
df_data$date<-as.Date(df_data$date,format="%Y%m%d") # isd() returns "YYYYMMDD" strings
df_data$temp<-as.numeric(df_data$temperature)/10
df_data$dew<-as.numeric(df_data$temperature_dewpoint)/10
df_data$wind_spd<-as.numeric(df_data$wind_speed)/10
df_data$slp<-as.numeric(df_data$air_pressure)/10
for(k in c("temp","dew","wind_spd","slp")) {
df_data[[k]]<-ifelse(df_data[[k]]>900|df_data[[k]]< -200,NA,df_data[[k]])
}
df_data<-df_data[!is.na(df_data$date),]
df_data[df_data==999.9]<-NA # catch any remaining sentinels
df_data$month<-sub("-\\d{2}$","",df_data$date) # "YYYY-MM" columnTwo-pass sentinel removal:
ifelse(x>900|x< -200,NA,x), for each of the four measures — catches the scaled sentinels immediately after divisiondf_data[df_data == 999.9] <- NA — safety net for any that slipped throughaggregate() applies a function (here max or min) to every numeric column, grouped by date or month. Columns are then renamed with _max / _min suffixes before merging.
measures<-names(df_data)[sapply(df_data,is.numeric)]
daily_max<-aggregate(df_data[measures],list(date=df_data$date),max,na.rm=TRUE)
daily_min<-aggregate(df_data[measures],list(date=df_data$date),min,na.rm=TRUE)
month_max<-aggregate(df_data[measures],list(month=df_data$month),max,na.rm=TRUE)
month_min<-aggregate(df_data[measures],list(month=df_data$month),min,na.rm=TRUE)
names(daily_max)[-1]<-paste0(names(daily_max)[-1],"_max")
names(daily_min)[-1]<-paste0(names(daily_min)[-1],"_min")
names(month_max)[-1]<-paste0(names(month_max)[-1],"_max")
names(month_min)[-1]<-paste0(names(month_min)[-1],"_min")
daily<-merge(daily_max,daily_min)
month<-merge(month_max,month_min)
daily$date<-as.Date(daily$date)
month$month_date<-as.Date(paste0(month$month,"-01"))
month<-month[order(month$month_date),] date temp_max temp_min wind_spd_max
1 2004-01-05 9 7 6.2
2 2004-01-06 9 2 8.7
3 2004-01-07 4 -3 8.2
4 2004-01-08 9 -5 4.6
5 2004-01-09 9 -1 3.1
6 2004-01-10 11 4 9.3
The charts share their colors, a dashed line at 0 °C, a time axis with one tick a year, and a helper that adds the title and the source:
# from cold (blue) to hot (red), for the highest temperatures
temp_colors<-c("#2166ac","#74add1","#fee090","#f46d43","#a50026")
temp_scale<-lapply(seq_along(temp_colors),
function(i) list((i-1)/(length(temp_colors)-1),temp_colors[i]))
# a dashed line at 0 °C, and a time axis with one tick a year
zero_line<-list(type="line",xref="paper",x0=0,x1=1,y0=0,y1=0,
line=list(color="white",width=1,dash="dash"))
years_axis<-list(tickformat="%Y",dtick="M12",tickangle=-90)
# the title of a chart, its source as a note under it, and the common layout
chart<-function(p,title,y_title="",x_axis=list(),y_axis=list(),annotations=list(),
note_y=-0.14,...) {
note<-list(text="Source: NOAA ISD via rnoaa",xref="paper",yref="paper",x=1,y=note_y,
xanchor="right",yanchor="top",showarrow=FALSE,font=list(size=10,color="#7F7F7F"))
result<-layout(p,title=list(text=title,x=0.02,xanchor="left"),
xaxis=modifyList(list(title=""),x_axis),
yaxis=modifyList(list(title=y_title),y_axis),
annotations=c(annotations,list(note)),...) %>%
config(displaylogo=FALSE)
return(result)
}
# the titles of panels stacked one above the other, each above its panel
panel_titles<-function(p,titles) {
domains<-plotly_build(p)$x$layout
axes<-c("yaxis",paste0("yaxis",seq_along(titles)[-1]))
result<-lapply(seq_along(titles),function(k) {
list(text=paste0("<b>",titles[k],"</b>"),x=0,xref="paper",xanchor="left",
y=domains[[axes[k]]]$domain[2],yref="paper",yanchor="bottom",showarrow=FALSE,
font=list(size=12))
})
return(result)
}Each day is a bar from its lowest to its highest temperature (a plotly bar with a base), and the bars side by side form a band. The color of each bar is mapped to temp_max through a diverging scale — cold days are blue, hot days are red.
# each day a bar from its lowest to its highest temperature, colored by the highest; alone: drawn
# on its own, with its color scale
daily_bars<-function(alone=TRUE) {
result<-plot_ly(daily,x=~date,y=~round(temp_max-temp_min,1),base=~temp_min,type="bar",
marker=list(color=~temp_max,colorscale=temp_scale,showscale=alone,opacity=0.7,
colorbar=list(title="Max °C")),
text=~paste0(format(date,"%d %b %Y"),": ",temp_min," to ",temp_max," °C"),
hoverinfo="text",textposition="none") %>%
layout(bargap=0,xaxis=years_axis,yaxis=list(zeroline=FALSE),shapes=list(zero_line))
return(result)
}
daily_bars() %>%
chart(paste0(str_aes(station),"<br><sup>Daily temperature range</sup>"),
y_title="Temperature (°C)")Aggregating to monthly level removes the noise and makes the seasonal pattern clearer. The max temperature gets points colored on the same scale; the min stays a white line.
# the range of each month, its highest temperature as points colored like the days, and its lowest
monthly_band<-function(alone=TRUE) {
result<-plot_ly(month,x=~month_date) %>%
add_ribbons(ymin=~temp_min,ymax=~temp_max,fillcolor=toRGB("#74add1",0.45),line=list(width=0),
hoverinfo="skip") %>%
add_lines(y=~temp_max,line=list(color="#9e9e9e",width=1),hoverinfo="skip") %>%
add_markers(y=~temp_max,
marker=list(color=~temp_max,colorscale=temp_scale,showscale=alone,size=6,
colorbar=list(title="Max °C")),
text=~paste0(format(month_date,"%b %Y"),": highest ",temp_max," °C"),
hoverinfo="text") %>%
add_lines(y=~temp_min,line=list(color="white",width=1.5),
text=~paste0(format(month_date,"%b %Y"),": lowest ",temp_min," °C"),
hoverinfo="text") %>%
layout(showlegend=FALSE,xaxis=years_axis,yaxis=list(zeroline=FALSE),shapes=list(zero_line))
return(result)
}
monthly_band() %>%
chart(paste0(str_aes(station),"<br><sup>Monthly temperature range</sup>"),
y_title="Temperature (°C)")A calendar heatmap puts year on the x-axis and month on the y-axis, with temperature encoded as fill color. This format is ideal for spotting anomalies — an unusually hot August or a cold February stands out immediately.
month$year<-substr(month$month,1,4)
month$mon<-substr(month$month,6,7)
# one measure as a calendar: years across, months up, the median of all months in the light middle
# color; alone: drawn on its own, with its color scale and the value in each cell
heat_panel<-function(column,alone=TRUE) {
z<-month[[column]]
middle<-(median(z)-min(z))/(max(z)-min(z))
result<-plot_ly(month,x=~year,y=~mon,z=z,type="heatmap",
colorscale=list(list(0,"#256abf"),list(middle,"#f0efec"),list(1,"#e34948")),
showscale=alone,xgap=1,ygap=1,text=paste0(round(z,1),"°C"),
texttemplate=if(alone) "%{text}" else "",textfont=list(size=9,color="#333333"),
hovertemplate="%{x}-%{y}: %{text}<extra></extra>",colorbar=list(title="°C")) %>%
layout(xaxis=list(type="category",tickangle=-90),
yaxis=list(type="category",categoryorder="array",categoryarray=sprintf("%02d",1:12)))
return(result)
}
heat_panel("temp_max") %>% chart("Monthly Max Temperature",note_y=-0.16)# the four charts one above the other; their color scales and values are in the charts above
together<-subplot(daily_bars(FALSE),monthly_band(FALSE),heat_panel("temp_max",FALSE),
heat_panel("temp_min",FALSE),nrows=4,margin=0.035)
titles<-c("Daily temperature range","Monthly temperature range","Monthly max temperature",
"Monthly min temperature")
together %>%
chart(str_aes(station),annotations=panel_titles(together,titles),showlegend=FALSE,note_y=-0.03,
margin=list(t=70,b=50))decompose() splits a time series into three additive components:
The frequency = 365 tells R the series repeats annually. The day of the year of the first date (format(first_day,"%j")) sets the correct starting position within the first year.
first_day<-min(daily$date)
ts_temp<-ts(daily$temp_max,frequency=365,
start=c(as.numeric(format(first_day,"%Y")),as.numeric(format(first_day,"%j"))))
fit<-decompose(ts_temp)
# the series and its three components, by date
components<-data.frame(date=daily$date,
Data=as.numeric(fit$x),
Trend=as.numeric(fit$trend),
Seasonal=as.numeric(fit$seasonal),
Random=as.numeric(fit$random))
components[-1]<-round(components[-1],2)
# one panel each; style() keeps one hover text for the whole line (given to plot_ly(), it would be
# repeated for every day)
panels<-lapply(names(components)[-1],function(k) {
plot_ly(components,x=~date,y=reformulate(k),type="scatter",mode="lines",
line=list(color="#404040",width=0.7)) %>%
style(hovertemplate=paste0(k,", %{x|%d %b %Y}: %{y:.1f} °C<extra></extra>"))
})
decomposition<-subplot(panels,nrows=4,shareX=TRUE,margin=0.04)
decomposition %>%
chart(paste0("Seasonal decomposition<br><sup>",str_aes(station),", daily max</sup>"),
x_axis=years_axis,annotations=panel_titles(decomposition,names(components)[-1]),
showlegend=FALSE,note_y=-0.08,margin=list(t=95))Reading the decomposition: If the trend panel slopes upward over 20+ years, that is a local warming signal. The random panel should look like white noise — large spikes indicate extreme weather events.
Change only these two lines and re-run everything:
Any ICAO code in the ISD station list will work. To search by country:
| Resource | URL |
|---|---|
| NOAA ISD | https://www.ncei.noaa.gov/products/land-based-station/integrated-surface-database |
| rnoaa package | https://github.com/ropensci/rnoaa |
| Station list | isd_stations() — cached locally after first call |
Rendered with R 4.6.2 · rnoaa · plotly
str_aes() on this page---
title: "Airport Weather Analysis with NOAA ISD"
description: "Download, clean and plot hourly NOAA ISD weather for any airport in R with rnoaa: daily and monthly temperature ribbons, heatmaps and seasonal decomposition."
author: ""
---
```{r setup, include=FALSE}
directory<-""
if(rstudioapi::isAvailable())
directory<-paste0(dirname(rstudioapi::getActiveDocumentContext()$path),"/")
source(paste0(directory,"R/code_options.R"))
source(paste0(directory,"R/code_rwf.R"))
```
## Overview
This tutorial shows how to download, clean, and visualize long-term weather data for any airport in the world using the **NOAA Integrated Surface Database (ISD)** — no FTP, no API key, no paid data.
The example uses **Athens Eleftherios Venizelos (LGAV)**, but every step works for any ICAO station code.
**Outputs:**
| Plot | What it shows |
|------|--------------|
| Daily ribbon | Temperature range (min–max) for every day |
| Monthly ribbon | Smoothed monthly range with gradient line |
| Heatmap max | Monthly max temperature by year |
| Heatmap min | Monthly min temperature by year |
| Decomposition | Trend + seasonal + residual components |
---
## Packages
```{r packages}
library(rnoaa)
library(plotly)
```
```{r install, eval=FALSE}
# remotes::install_github("ropensci/rnoaa") # use the GitHub version
# install.packages("plotly")
```
---
## 1. Find the station
NOAA ISD identifies stations by **USAF** and **WBAN** codes. The easiest way to find them is by ICAO airport code.
```{r station}
stations<-isd_stations(refresh=FALSE)
# explore Greek stations
stations[stations$ctry%in%"GR",c("station_name","icao","usaf","wban","lat","lon")]
```
```{r lgav}
lgav<-stations[stations$icao%in%"LGAV",]
station<-lgav$station_name
usaf<-lgav$usaf[1]
wban<-lgav$wban[1]
message("Station : ",station)
message("USAF : ",usaf," WBAN: ",wban)
message("Location: ",round(lgav$lat[1],3),"°N ",round(lgav$lon[1],3),"°E")
```
> Change `"LGAV"` to any ICAO code — `"EGLL"` for Heathrow, `"KJFK"` for New York, etc.
---
## 2. Download hourly ISD data
`rnoaa::isd()` replaces the old wget + FTP workflow. It downloads, decompresses, and parses the ISD binary format automatically. Each call fetches one year; a loop collects all years into a list.
```{r download}
years<-2001:2026
data_list<-list()
for(yr in years) {
tryCatch({
d<-rnoaa::isd(usaf=usaf,wban=wban,year=yr,progress=FALSE)
data_list[[as.character(yr)]]<-d
message(" downloaded ",yr," (",nrow(d)," rows)")
},error=function(e) message(" skip ",yr,": ",conditionMessage(e)))
}
# the years do not all have the same columns: give each year every column, NA where it has none
columns<-unique(unlist(lapply(data_list,names)))
data_list<-lapply(data_list,function(d) {
d<-as.data.frame(d)
d[setdiff(columns,names(d))]<-NA
d[columns]
})
df_raw<-do.call(rbind,data_list)
rownames(df_raw)<-NULL
message("Total rows: ",nrow(df_raw))
```
> Years where data are unavailable are silently skipped by `tryCatch`. 2026 data may be partial depending on when you run this.
---
## 3. Clean: sentinel values and date parsing
### Why sentinel values matter
NOAA ISD encodes missing measurements as **9999** in the raw file. After dividing by 10 (ISD stores all values as tenths of the unit), missing temperature becomes **999.9°C** — a physically impossible value that will corrupt any aggregate (mean, max, min) if not removed.
```{r clean}
df_data<-df_raw
df_data$date<-as.Date(df_data$date,format="%Y%m%d") # isd() returns "YYYYMMDD" strings
df_data$temp<-as.numeric(df_data$temperature)/10
df_data$dew<-as.numeric(df_data$temperature_dewpoint)/10
df_data$wind_spd<-as.numeric(df_data$wind_speed)/10
df_data$slp<-as.numeric(df_data$air_pressure)/10
for(k in c("temp","dew","wind_spd","slp")) {
df_data[[k]]<-ifelse(df_data[[k]]>900|df_data[[k]]< -200,NA,df_data[[k]])
}
df_data<-df_data[!is.na(df_data$date),]
df_data[df_data==999.9]<-NA # catch any remaining sentinels
df_data$month<-sub("-\\d{2}$","",df_data$date) # "YYYY-MM" column
```
**Two-pass sentinel removal:**
1. `ifelse(x>900|x< -200,NA,x)`, for each of the four measures — catches the scaled sentinels immediately after division
2. `df_data[df_data == 999.9] <- NA` — safety net for any that slipped through
---
## 4. Daily and monthly aggregates
`aggregate()` applies a function (here `max` or `min`) to every numeric column, grouped by date or month. Columns are then renamed with `_max` / `_min` suffixes before merging.
```{r aggregate}
measures<-names(df_data)[sapply(df_data,is.numeric)]
daily_max<-aggregate(df_data[measures],list(date=df_data$date),max,na.rm=TRUE)
daily_min<-aggregate(df_data[measures],list(date=df_data$date),min,na.rm=TRUE)
month_max<-aggregate(df_data[measures],list(month=df_data$month),max,na.rm=TRUE)
month_min<-aggregate(df_data[measures],list(month=df_data$month),min,na.rm=TRUE)
names(daily_max)[-1]<-paste0(names(daily_max)[-1],"_max")
names(daily_min)[-1]<-paste0(names(daily_min)[-1],"_min")
names(month_max)[-1]<-paste0(names(month_max)[-1],"_max")
names(month_min)[-1]<-paste0(names(month_min)[-1],"_min")
daily<-merge(daily_max,daily_min)
month<-merge(month_max,month_min)
daily$date<-as.Date(daily$date)
month$month_date<-as.Date(paste0(month$month,"-01"))
month<-month[order(month$month_date),]
```
```{r aggregate_preview}
head(daily[,c("date","temp_max","temp_min","wind_spd_max")],6)
```
---
## 5. Plots
The charts share their colors, a dashed line at 0 °C, a time axis with one tick a year, and a helper that adds the title and the source:
```{r chart_style}
# from cold (blue) to hot (red), for the highest temperatures
temp_colors<-c("#2166ac","#74add1","#fee090","#f46d43","#a50026")
temp_scale<-lapply(seq_along(temp_colors),
function(i) list((i-1)/(length(temp_colors)-1),temp_colors[i]))
# a dashed line at 0 °C, and a time axis with one tick a year
zero_line<-list(type="line",xref="paper",x0=0,x1=1,y0=0,y1=0,
line=list(color="white",width=1,dash="dash"))
years_axis<-list(tickformat="%Y",dtick="M12",tickangle=-90)
# the title of a chart, its source as a note under it, and the common layout
chart<-function(p,title,y_title="",x_axis=list(),y_axis=list(),annotations=list(),
note_y=-0.14,...) {
note<-list(text="Source: NOAA ISD via rnoaa",xref="paper",yref="paper",x=1,y=note_y,
xanchor="right",yanchor="top",showarrow=FALSE,font=list(size=10,color="#7F7F7F"))
result<-layout(p,title=list(text=title,x=0.02,xanchor="left"),
xaxis=modifyList(list(title=""),x_axis),
yaxis=modifyList(list(title=y_title),y_axis),
annotations=c(annotations,list(note)),...) %>%
config(displaylogo=FALSE)
return(result)
}
# the titles of panels stacked one above the other, each above its panel
panel_titles<-function(p,titles) {
domains<-plotly_build(p)$x$layout
axes<-c("yaxis",paste0("yaxis",seq_along(titles)[-1]))
result<-lapply(seq_along(titles),function(k) {
list(text=paste0("<b>",titles[k],"</b>"),x=0,xref="paper",xanchor="left",
y=domains[[axes[k]]]$domain[2],yref="paper",yanchor="bottom",showarrow=FALSE,
font=list(size=12))
})
return(result)
}
```
### Daily temperature ribbon
Each day is a bar from its lowest to its highest temperature (a plotly bar with a `base`), and the bars side by side form a band. The color of each bar is mapped to `temp_max` through a diverging scale — cold days are blue, hot days are red.
```{r plot_daily, fig.width = 10}
# each day a bar from its lowest to its highest temperature, colored by the highest; alone: drawn
# on its own, with its color scale
daily_bars<-function(alone=TRUE) {
result<-plot_ly(daily,x=~date,y=~round(temp_max-temp_min,1),base=~temp_min,type="bar",
marker=list(color=~temp_max,colorscale=temp_scale,showscale=alone,opacity=0.7,
colorbar=list(title="Max °C")),
text=~paste0(format(date,"%d %b %Y"),": ",temp_min," to ",temp_max," °C"),
hoverinfo="text",textposition="none") %>%
layout(bargap=0,xaxis=years_axis,yaxis=list(zeroline=FALSE),shapes=list(zero_line))
return(result)
}
daily_bars() %>%
chart(paste0(str_aes(station),"<br><sup>Daily temperature range</sup>"),
y_title="Temperature (°C)")
```
### Monthly ribbon
Aggregating to monthly level removes the noise and makes the seasonal pattern clearer. The max temperature gets points colored on the same scale; the min stays a white line.
```{r plot_monthly, fig.width = 10}
# the range of each month, its highest temperature as points colored like the days, and its lowest
monthly_band<-function(alone=TRUE) {
result<-plot_ly(month,x=~month_date) %>%
add_ribbons(ymin=~temp_min,ymax=~temp_max,fillcolor=toRGB("#74add1",0.45),line=list(width=0),
hoverinfo="skip") %>%
add_lines(y=~temp_max,line=list(color="#9e9e9e",width=1),hoverinfo="skip") %>%
add_markers(y=~temp_max,
marker=list(color=~temp_max,colorscale=temp_scale,showscale=alone,size=6,
colorbar=list(title="Max °C")),
text=~paste0(format(month_date,"%b %Y"),": highest ",temp_max," °C"),
hoverinfo="text") %>%
add_lines(y=~temp_min,line=list(color="white",width=1.5),
text=~paste0(format(month_date,"%b %Y"),": lowest ",temp_min," °C"),
hoverinfo="text") %>%
layout(showlegend=FALSE,xaxis=years_axis,yaxis=list(zeroline=FALSE),shapes=list(zero_line))
return(result)
}
monthly_band() %>%
chart(paste0(str_aes(station),"<br><sup>Monthly temperature range</sup>"),
y_title="Temperature (°C)")
```
### Heatmaps
A calendar heatmap puts **year on the x-axis** and **month on the y-axis**, with temperature encoded as fill color. This format is ideal for spotting anomalies — an unusually hot August or a cold February stands out immediately.
```{r heatmaps, fig.width = 10}
month$year<-substr(month$month,1,4)
month$mon<-substr(month$month,6,7)
# one measure as a calendar: years across, months up, the median of all months in the light middle
# color; alone: drawn on its own, with its color scale and the value in each cell
heat_panel<-function(column,alone=TRUE) {
z<-month[[column]]
middle<-(median(z)-min(z))/(max(z)-min(z))
result<-plot_ly(month,x=~year,y=~mon,z=z,type="heatmap",
colorscale=list(list(0,"#256abf"),list(middle,"#f0efec"),list(1,"#e34948")),
showscale=alone,xgap=1,ygap=1,text=paste0(round(z,1),"°C"),
texttemplate=if(alone) "%{text}" else "",textfont=list(size=9,color="#333333"),
hovertemplate="%{x}-%{y}: %{text}<extra></extra>",colorbar=list(title="°C")) %>%
layout(xaxis=list(type="category",tickangle=-90),
yaxis=list(type="category",categoryorder="array",categoryarray=sprintf("%02d",1:12)))
return(result)
}
heat_panel("temp_max") %>% chart("Monthly Max Temperature",note_y=-0.16)
heat_panel("temp_min") %>% chart("Monthly Min Temperature",note_y=-0.16)
```
### All four together
```{r multiplot, fig.height = 14, fig.width = 10}
# the four charts one above the other; their color scales and values are in the charts above
together<-subplot(daily_bars(FALSE),monthly_band(FALSE),heat_panel("temp_max",FALSE),
heat_panel("temp_min",FALSE),nrows=4,margin=0.035)
titles<-c("Daily temperature range","Monthly temperature range","Monthly max temperature",
"Monthly min temperature")
together %>%
chart(str_aes(station),annotations=panel_titles(together,titles),showlegend=FALSE,note_y=-0.03,
margin=list(t=70,b=50))
```
---
## 6. Seasonal decomposition
`decompose()` splits a time series into three additive components:
- **Trend** — the long-term direction (is the station getting warmer?)
- **Seasonal** — the repeating annual cycle (summer peaks, winter troughs)
- **Random** — what's left after removing trend and seasonal (unusual events, measurement noise)
The `frequency = 365` tells R the series repeats annually. The day of the year of the first date (`format(first_day,"%j")`) sets the correct starting position within the first year.
```{r decomp, fig.width = 10, fig.height = 8}
first_day<-min(daily$date)
ts_temp<-ts(daily$temp_max,frequency=365,
start=c(as.numeric(format(first_day,"%Y")),as.numeric(format(first_day,"%j"))))
fit<-decompose(ts_temp)
# the series and its three components, by date
components<-data.frame(date=daily$date,
Data=as.numeric(fit$x),
Trend=as.numeric(fit$trend),
Seasonal=as.numeric(fit$seasonal),
Random=as.numeric(fit$random))
components[-1]<-round(components[-1],2)
# one panel each; style() keeps one hover text for the whole line (given to plot_ly(), it would be
# repeated for every day)
panels<-lapply(names(components)[-1],function(k) {
plot_ly(components,x=~date,y=reformulate(k),type="scatter",mode="lines",
line=list(color="#404040",width=0.7)) %>%
style(hovertemplate=paste0(k,", %{x|%d %b %Y}: %{y:.1f} °C<extra></extra>"))
})
decomposition<-subplot(panels,nrows=4,shareX=TRUE,margin=0.04)
decomposition %>%
chart(paste0("Seasonal decomposition<br><sup>",str_aes(station),", daily max</sup>"),
x_axis=years_axis,annotations=panel_titles(decomposition,names(components)[-1]),
showlegend=FALSE,note_y=-0.08,margin=list(t=95))
```
> **Reading the decomposition:** If the trend panel slopes upward over 20+ years, that is a local warming signal. The random panel should look like white noise — large spikes indicate extreme weather events.
---
## Adapting to another airport
Change only these two lines and re-run everything:
```{r other_station, eval=FALSE}
lgav<-stations[stations$icao%in%"EGLL",] # London Heathrow
years<-2000:2026
```
Any ICAO code in the ISD station list will work. To search by country:
```{r search, eval=FALSE}
stations[stations$ctry%in%"UK",c("station_name","icao","usaf","wban")]
```
---
## Data source
| Resource | URL |
|----------|-----|
| NOAA ISD | `https://www.ncei.noaa.gov/products/land-based-station/integrated-surface-database` |
| rnoaa package | `https://github.com/ropensci/rnoaa` |
| Station list | `isd_stations()` — cached locally after first call |
---
*Rendered with R `r getRversion()` · rnoaa · plotly*