rm(list=ls())

fmi <- readRDS("FMI_monthly_clim_polygons.RDS")
era5 <- readRDS("ERA5L_monthly_clim_polygons.RDS")

diff <- era5

diff$data <- era5$data - fmi$data

library(maptools)

mask.file <- paste0("/esarchive/shapefiles/",
  'NUTS/ref-nuts-2021-20m.shp/NUTS_RG_20M_2021_4326_LEVL_2.shp/NUTS_RG_20M_2021_4326_LEVL_2.shp')
shp_eu <- rgdal::readOGR(mask.file)
shp_fi <- subset(shp_eu, CNTR_CODE == "FI")
##     plot(shp_fi)
#LAUS
mask.file_laus <- paste0("/esarchive/shapefiles/", '/LAU/LAU_RG_01M_2020_4326.shp')
shp_laus <- rgdal::readOGR(mask.file_laus)
shp_laus <- subset(shp_laus, CNTR_CODE == "FI")
Laus_lapland <- c('047', '148', '240', '320', '241', '261', '273', '498', '583', '854',
                  '614', '683', '698', '732', '742', '751', '758', '845', '851', '890',
                  '976')
shp_lapland <- subset(shp_laus, LAU_ID %in% Laus_lapland)
##     plot(shp_lapland)

# Subset region
lat_min <- 65#59
lat_max <- 71
lon_min <- 20
lon_max <- 31

library(sf)
library(ggplot2)
#library(ggplot2, lib.loc = .libPaths()[2])
library(RColorBrewer)
library(rgeos)

gusa <- map_data("world")


plot_poly <- list()
for (mes in 1:12) {
print(mes)
  df.df <- subset(diff, mon == mes)
mon <- mes
 plot_poly[[mon]] <- ggplot(data = df.df) +
        geom_polygon(aes(long, lat, group = group),fill = "lightgrey", data = gusa) +
        coord_map(projection = "stereographic",
                  xlim = c(lon_min, lon_max),
                  ylim = c(lat_min, lat_max)) +
        geom_polygon(aes(x = long, y = lat, fill = cut(data,
                                          breaks = seq(-1.6, 1.6, 0.2)),
                     group = group), color = "grey",size = 0.08) +
        geom_polygon(aes(x = long, y = lat, group = group), fill = NA,
                    color = "grey", size = 0.5, data = shp_lapland) +
        theme_bw() +
        scale_fill_manual(values = c(rev(brewer.pal(9, 'Blues')),
                                     brewer.pal(8, 'Reds'), "black"),
                          drop = FALSE, name = 'tas(ºC)') +
        theme(panel.background = element_rect(fill = 'azure'),
              text = element_text(family = "Times")) +  # Colour of ocean
        xlab('Longitude') + ylab('Latitude') +
        scale_x_continuous(breaks = seq(-12, 45, 4),labels = waiver()) +
        scale_y_continuous(breaks = seq(32, 70, 4),labels = waiver()) +
        ggtitle(month.name[mon])# +
}

library(ggpubr)

plot <- ggarrange(plotlist = plot_poly, ncol = 6, nrow = 2, common.legend = TRUE, legend = "bottom")
plot <- annotate_figure(plot, top = text_grob("ERA5Land - FMI Monthly clim 1993-2021",
                        color = "black", face = "bold", size = 14))
ggsave("Diff_FMI-ERA5L_tas_polys.jpg", plot, width = 18, height = 13, bg = 'white')


