# Base de données européenne Tradeve : import et traitement
# Jeu de données : historique des populations communales, Insee
# #!!! il peut y avoir des bugs selon les versions de Rstudio : le script marche avec la version 2021.09.2+382

# 1.  Préparer l'interface -------------------------------------
# 1.1 Charger les extensions====================================
library(here)
library(tidyverse)
# Import de tables
library(readxl)
library(openxlsx)
# Statistiques
# library(questionr)
# library(foreign)
# library(psych)
# Texte 
library(showtext)
# Cartographie
library(sf)
library(leaflet)
library(crosstalk)
# Visualisation
# library(shiny)
library(esquisse)
library(plotly) # interactivité maximale
library(gganimate) # animation
library(gifski)# export animation
# library(ggiraph) # interactivité minimale
# library(ggiraphExtra)
library(crosstalk)
library(gghighlight) # surligner certaines données
# library(ggdist) # incertitude et intervalle de confiance
library(withr)
library(htmltools)
library(htmlwidgets)
library(rmarkdown)
# Gestion des étiquettes sur les graphiques
library(ggrepel)
# library(geomtextpath) # étiquette le long d'une ligne, incompatible avec shiny
# library(directlabels) # étiquettes pour situations complexes
# Archives
library(archive)
library(zip) # unzip file.zip
library(R.utils) # unzip file.gz
# Mesures
library(measurements)
# Données Eurostat
library(eurostat)
library(giscoR)
library(widgetframe)

# 1.2 Gérer ses polices de caractères personelles ===============
# #Importer et afficher avec showtext
# # Vérifier le chemin d'installation des polices sur le système
font_paths()
# # Ajouter la police
font_add(family = "DejaVuSans", regular = "C://Windows//Fonts/DejaVuSans.ttf", bold ="C://Windows//Fonts/DejaVuSans-Bold.ttf", italic = "C://Windows//Fonts/DejaVuSans-Oblique.ttf", bolditalic = "C://Windows//Fonts/DejaVuSans-BoldOblique.ttf" )
font_add(family = "DejaVuSansCondensed", regular = "C://Windows//Fonts/DejaVuSansCondensed.ttf", bold ="C://Windows//Fonts/DejaVuSansCondensed-Bold.ttf", italic = "C://Windows//Fonts/DejaVuSansCondensed-Oblique.ttf", bolditalic = "C://Windows//Fonts/DejaVuSansCondensed-BoldOblique.ttf" )
# # regarder les familles installées sur le systèmepour vérifier que ces familles ont été ajoutées
sysfonts::font_families()
# # Activer showtext pour l'ensemble des graphiques du script
showtext_auto()

# 1.3 Encoder les données ===============
locale( encoding = "UTF-8")

# 1.4 Déclarer la racine du projet =============================================
here::i_am("Tradeve/00-R_scripts/Tradeve.R")

# 1.5 Travailler sur le script ===================================
# Pour transformer un code en commentaire ou un commentaire en code
# Sélectionner les lignes de codes concernées PUIS Ctrl+Shift+c
# 1.6 Se connecter à Nextcloud----------------------
# remotes::install_github("KWB-R/kwb.nextcloud")
# library(kwb.nextcloud)
# configurer pour la première fois l'environnement de R pour qu'il contienne la clef d'API INSEE dans R
# usethis::edit_r_environ()

# 2.  Importer et gérer des données------------

#2.1 Import des données et visualisations des données TRADEVE========================
# url <- "https://tradeve.parisgeo.cnrs.fr/tradeve.zip"
# download.file(url, 
#               destfile = "./01-Input_data/tradeve.zip", 
#               method = "curl")
# archive_extract(
#   "./01-Input_data/tradeve.zip",
#   dir = "./01-Input_data/")
# file.remove("./01-Input_data/tradeve.zip")

Tradeve <- read_excel("./01-Input_data/TRADEVE_database/TRADEVE_UrbanAreas_Data.xlsx",
                          sheet = "UrbanAreas_Data")

TradeveCarte2011 <- st_read("./01-Input_data/TRADEVE_database/TRADEVE_UrbanAreas_Perimeters/UA_perimeter2001_Pop1961_2011.shp")

#2.2 Import des données et visualisations des données LAU==============================
#https://ec.europa.eu/eurostat/fr/web/gisco/geodata/reference-data/administrative-units-statistical-units/lau
# https://ropengov.github.io/giscoR/reference/gisco_get_lau.html
# LAUdata2011<- gisco_get_lau(
#   year = "2011",
#   epsg = "3035",
#   cache = TRUE,
#   update_cache = FALSE,
#   cache_dir = NULL,
#   verbose = FALSE,
#   country = NULL,
#   gisco_id = NULL
# )
# LAUdata2011<- LAUdata2011%>%
#   rename(DENS_2011=POP_DENS_2011)%>%
#   select("GISCO_ID","CNTR_CODE","LAU_ID","LAU_NAME","POP_2011","DENS_2011","AREA_KM2","YEAR","FID")
# 
# st_write(LAUdata2011,
#   "./01-Input_data/LAU_RG_01M_2011.xlsx",
#   layer = "LAU_RG_01M_2011_3035",
#   driver = "XLSX")

LAUdata2011 <- read_excel("./01-Input_data/LAU_RG_01M_2011.xlsx",
                      sheet = "LAU_RG_01M_2011_3035")


#2.3 Calculs pour les tables Tradeve ==============================

# Attention : les aires urbaines irlandaises (sud et nord) sont écrites en Majuscules > les mettre en format "Title"
Tradeve <- Tradeve%>%
  mutate(Name=case_when(Country=="IE"~str_to_title(Name),
                        TRUE~Name))%>%
  mutate(Name=case_when(Country=="UK"~str_to_title(Name),
                        TRUE~Name))

## Tradeve : Calcul des augmentations annuelles de densités selon les périodes------------------
Tradeve$Dens_1961 <- Tradeve$Pop_1961/Tradeve$Area_1961
Tradeve$Dens_1971 <- Tradeve$Pop_1971/Tradeve$Area_1971
Tradeve$Dens_1981 <- Tradeve$Pop_1981/Tradeve$Area_1981
Tradeve$Dens_1991 <- Tradeve$Pop_1991/Tradeve$Area_1991
Tradeve$Dens_2001 <- Tradeve$Pop_2001/Tradeve$Area_2001
Tradeve$Dens_2011 <- Tradeve$Pop_2011/Tradeve$Area_2011

Tradeve$D2011_1961 <- Tradeve$Dens_2011-Tradeve$Dens_1961
Tradeve$D2001_1961 <- Tradeve$Dens_2001-Tradeve$Dens_1961
Tradeve$D2011_2001 <- Tradeve$Dens_2011-Tradeve$Dens_2001
Tradeve$DA2001_1961 <- Tradeve$D2001_1961/(2001-1961)
Tradeve$DA2011_2001 <- Tradeve$D2011_2001/(2011-2001)
Tradeve$DA2011_1961 <- Tradeve$D2011_1961/(2011-1961)

# Arrondir à deux chiffres après la virgule
Tradeve<- Tradeve %>%
  mutate_at(20:31, round, 2)


##Examiner le jeu de données-----------------------------------------------------------------------
str(Tradeve)
typeof(Tradeve$Pop_1961)
class(Tradeve$Pop_1961)
nrow(Tradeve)
ncol(Tradeve)
dim(Tradeve)
names(Tradeve)

##Organiser et nettoyer les données----------------------------------------------------------------------------
TradeveLight <- Tradeve%>%
  select(1:3,5,8:25)


# Pour effectuer un pivot_longer sur plusieurs colonnes en même temps, on utilise des expressions regex
# "names_pattern" définit le fait que le nom est constitué de deux données différentes : le type de valeur et l'année, séparés par un underscore
# "names_to" utilise cette situation pour définir un objectif d'organisation de pivot_longer en différentes colonnes
#  dans lesquelles l'année (en suffixe) est unique et les autres colonnes correspondent au préfixe de colonne de départ
TradeveLonger <- TradeveLight %>%
  pivot_longer(
    cols=Pop_1961:Dens_2011,
    names_pattern="(.*)_(.*)",
    names_to= c(".value","Annee")
  )%>%
  rename(ID_UMZ="Unit_Code_Retro", Nom="Name", Pays="Country",Population="Pop", Surface="Area", Densite="Dens")

TradeveToJoin <- Tradeve%>%
  select(2,31)

TradeveLonger <- TradeveLonger%>%
  left_join(y=TradeveToJoin, by=c("ID_UMZ" = "Unit_Code_Retro"))

# Filtrer par année
TradeveLonger1961 <- TradeveLonger%>%
  filter(Annee==1961)
TradeveLonger1971 <- TradeveLonger%>%
  filter(Annee==1971)
TradeveLonger1981 <- TradeveLonger%>%
  filter(Annee==1981)
TradeveLonger1991 <- TradeveLonger%>%
  filter(Annee==1991)
TradeveLonger2001 <- TradeveLonger%>%
  filter(Annee==2001)
TradeveLonger2011 <- TradeveLonger%>%
  filter(Annee==2011)

# Filtrer par années de début de fin
TradeveLonger1961_2011 <- TradeveLonger%>%
  filter(Annee=="1961"| Annee=="2011")

# Filtrer par années de début de fin et par pays
TradeveLongerFR1961_2011 <- TradeveLonger1961_2011%>%
  filter(Pays=="FR")

# Séparer selon les dates
TradeveLongerFR1961 <- TradeveLonger1961_2011%>%
  filter(Annee=="1961")

TradeveLongerFR2011 <- TradeveLonger1961_2011%>%
  filter(Annee=="2011")

## Correlations entre surfaces et populations-------------------------------------------
# wilcox.test(TradeveLonger$Population ~ TradeveLonger$Surface,na.rm = TRUE)
# A verifier

## Statistiques de base, exportables (dyplr)---------------------------------------------------
SUM_TRA_Pop<-TradeveLonger %>%
  group_by(Annee)%>%
  summarise ('Min' = min (Population, na.rm = TRUE),
             '1er quantile'= quantile (Population, prob = 0.25, na.rm = TRUE),
             'Mediane'= median (Population, na.rm = TRUE),
             '3e quantile'= quantile (Population, prob = 0.75, na.rm = TRUE),
             'Max'= max (Population, na.rm = TRUE),
             'Moyenne'= mean(Population, na.rm = TRUE))
write.xlsx(SUM_TRA_Pop,file="./01-Input_data/SUM_TRA_Pop.xlsx", colNames = TRUE, sheetName="Population",borders = "columns" )
SUM_TRA_Area<-TradeveLonger%>%
  group_by(Annee)%>%
  summarise ('Min' = min (Surface, na.rm = TRUE),
             '1er quantile'= quantile (Surface,0.25, na.rm = TRUE),
             'Mediane'= median (Surface, na.rm = TRUE),
             '3e quantile'= quantile (Surface,0.75, na.rm = TRUE),
             'Max'= max (Surface, na.rm = TRUE),
             'Moyenne'= mean(Surface, na.rm = TRUE))
write.xlsx(SUM_TRA_Area,file="./01-Input_data/SUM_TRA_Area.xlsx", colNames = TRUE, sheetName="Surface",borders = "columns" )
SUM_TRA_Dens<-TradeveLonger %>%
  group_by(Annee)%>%
  summarise ('Min' = min (Densite, na.rm = TRUE),
             '1er quantile'= quantile (Densite, prob = 0.25, na.rm = TRUE),
             'Mediane'= median (Densite, na.rm = TRUE),
             '3e quantile'= quantile (Densite, prob = 0.75, na.rm = TRUE),
             'Max'= max (Densite, na.rm = TRUE),
             'Moyenne'= mean(Densite, na.rm = TRUE))
write.xlsx(SUM_TRA_Dens,file="./01-Input_data/SUM_TRA_Dens.xlsx", colNames = TRUE, sheetName="Densite",borders = "columns" )

##--------------------------------------------------------------------------------------------------
##LAU Préparation Croatie---------------------------------------------------------------------------
# Partie à compléter pour expliquer où on a été chercher les données communales
# ## LAU_READ-----------------------------------------------------------------------------------------
# LAUT <- read_excel("./01-Input_data/LAU2_TEMP.xlsx",
#                       sheet = "LAU2_TEMP")
# LAUT2 <- filter(LAUT, CNTR_CODE=="HR")
# 
# LAUT2$LAU2_ID2<-str_trunc(LAUT2$LAU2_ID, 5, side = c("left"), ellipsis = "")
# 
# write.xlsx(LAUT2,file="LAUT2.xlsx", colNames = TRUE, sheetName="LAU_TEMP2",borders = "columns" )
# ##--------------------------------------------------------------------------------------------------
# ## LAU AND TRADEVE READ ----------------------------------------------------------------------------
LAUTRA <- read_excel("./01-Input_data/LAU_UMZ_FUSION_PT_UMZ.xlsx",
                   sheet = "LAU_UMZ_FUSION_PT_UMZ")

# LTt1 <- read_excel("./01-Input_data/LAU_UMZ_FUSION_PT_Table1.xlsx",
#                      sheet = "LAU_UMZ_FUSION_PT_Table1")
# 
# LTt2 <- read_excel("./01-Input_data/LAU_UMZ_FUSION_PT_Table2.xlsx",
#                    sheet = "LAU_UMZ_FUSION_PT_Table2")
# 
# ## LAU AND TRADEVE FILTER 2011 ----------------------------------------------------------------------
names(LAUTRA)
str(LAUTRA)
typeof(LAUTRA$ID)

LAUTRA <-LAUTRA %>%
  select(1:31)

LAUTRA2011 <- LAUTRA%>%
  filter(DATA_DATE==2011)



# Fonctions
# Thèmes communs aux graphiques--------------------------------------------------
# Thème sans grille secondaire
ThemeFunction <- theme_light(base_family = "'DejaVuSansCondensed', arial narrow, sans-serif")+
  theme(plot.margin=margin(18,12,18,12,"pt"),
        plot.title =element_text(face="bold",lineheight = 1.5),
        panel.border = element_rect(fill = NA, colour = "grey",size = 0.1,linetype = "solid"),
        panel.spacing = unit(1,"lines"),
        panel.grid.minor = element_blank(),
        title = element_text(face = "bold", size=14),
        strip.text.x = element_text(face = "bold", size=12),
        axis.title=element_text(face = "bold", size=12),
        axis.text =element_text(size = rel(0.7), lineheight = 2),
        legend.title =element_text(face = "bold", size=12,lineheight=1.15),
        legend.position = c(.98, .98),
        legend.justification = c("right", "top"),
        legend.box.just = "right",
        plot.caption = element_text(size = 10, face="plain"))

# Thème avec grille secondaire
ThemeFunction2 <- theme_light(base_family = "'DejaVuSansCondensed', arial narrow, sans-serif")+
  theme(plot.margin=margin(18,12,18,12,"pt"),
      plot.title =element_text(face="bold",lineheight = 1.5),
      panel.border = element_rect(fill = NA, colour = "grey",size = 0.1,linetype = "solid"),
      panel.spacing = unit(1,"lines"),
      panel.grid.minor = element_line(linetype = "dotted", size=0.2),
      title = element_text(face = "bold", size=14),
      strip.text.x = element_text(face = "bold", size=12),
      axis.title=element_text(face = "bold", size=12),
      axis.text =element_text(size = rel(0.7), lineheight = 2),
      legend.title =element_text(face = "bold", size=12, lineheight=1.15),
      legend.position = c(.98, .98),
      legend.justification = c("right", "top"),
      legend.box.just = "right",
      plot.caption = element_text(size = 10, face="plain"))

# Raccourcis pour les graphiques
# Sources de données
SourceTradeve<- "Calculs: NLG. Source : Tradeve database"

# Ajouter des axes au graphique
AxesXY<- function(Graphique){
  OK<-Graphique+
    geom_vline(aes(xintercept=0),
                    linetype="dashed",
                    color="black",
                    size=0.5)+
    geom_hline(aes(yintercept=0),
               linetype="dashed",
               color="black",
               size=0.5)
  return(OK)
}
  

# Fonction d'impression standard ---------------------------------------------------------------------------------------------------
ImprimerPng <- function (NOM_GRAPHIQUE, NOM_FICHIER){
  OK<-ggsave(filename=paste0(NOM_FICHIER,"_1240.png"),
             plot = NOM_GRAPHIQUE,
             path = "./03-Output_figures",
             width = 1240,
             height = 1240,
             units = c("px"),
             dpi = 72)
  return(OK)
}

ImprimerTiff <- function (NOM_GRAPHIQUE, NOM_FICHIER){
  OK<-ggsave(filename=paste0(NOM_FICHIER,"_1240.tiff"),
             plot = NOM_GRAPHIQUE,
             path = "./03-Output_figures",
             width = 1240,
             height = 1240,
             units = c("px"),
             dpi = 72)
  return(OK)
}

ImprimerPdf <- function (NOM_GRAPHIQUE, NOM_FICHIER){
  OK<-ggsave(filename=paste0(NOM_FICHIER,"_1240.pdf"),
             plot = NOM_GRAPHIQUE,
             path = "./03-Output_figures",
             width = 1240,
             height = 1240,
             units = c("px"),
             dpi = 72)
  return(OK)
}


# Configuration de Plotly---------------------------------------------------------------------------------------------------
ConfigPlotly1 <- function(p) {
  OK<-config(p,
             locale ="fr",
             scrollZoom = TRUE, 
             displayModeBar = TRUE,
             displaylogo = FALSE,
             modeBarButtonsToRemove = c('select', 'select2d','lasso2d','resetScale2d','hoverCompareCartesian', 'resetViews'),
             modeBarButtonsToAdd = c('toggleSpikelines'),
             toImageButtonOptions = list(format= 'png', # one of png, svg, jpeg, webp,
                                         filename= 'Diagramme personnalisé',
                                         height= 1240,
                                         width= 1550,
                                         scale= 1 ),
             plotGlPixelRatio = 1,
             responsive=TRUE
  )
  return(OK)
}

ConfigPlotly2 <- function(p) {
  OK<-config(p,
             locale ="fr",
             scrollZoom = FALSE, 
             displayModeBar = TRUE,
             displaylogo = FALSE,
             modeBarButtonsToRemove = c('select', 'select2d','lasso2d','resetScale2d','hoverCompareCartesian', 'autoScale','resetScale'),
             modeBarButtonsToAdd = c('toggleSpikelines'),
             toImageButtonOptions = list(format= 'png', # one of png, svg, jpeg, webp,
                                         filename= 'Diagramme personnalisé',
                                         height= 1240,
                                         width= 1550,
                                         scale= 1 ),
             plotGlPixelRatio = 1,
             responsive=TRUE
  )
  return(OK)
}

# Autres fonctions de configuration
# https://plotly.com/r/configuration-options/#configuration-options
# https://github.com/plotly/plotly.js/blob/master/src/plot_api/plot_config.js
# https://plotly-r.com/improving-ggplotly.html
# https://plotly-r.com/saving.html
# showTips = FALSE # ne pas afficher le tooltip
# showSources = TRUE # Il faut ajouter une source pour que cela fonctionne
# modeBarButtons = # pour définir par un vecteur le contenu de la barre d'outils
# edits = list( annotationPosition = TRUE,
# annotationTail = TRUE,
# annotationText = TRUE,
# axisTitleText= TRUE,
# colorbarPosition = TRUE,
# colorbarTitleText= TRUE,
# legendPosition = TRUE,
# legendText=TRUE,
# shapePosition=TRUE,
# titleText=TRUE
# ) # Pour modifier de façon interactive les annotations sur les cartes
# frameMargins = 0 # margin when 'layout.autosize' is turned on min =0, max =0.5.
# doubleClick = [false, 'reset', 'autosize', 'reset+autosize']
# plotGlPixelRatio = 2 # min=2, max=4
# topojsonURL = 'https://cdn.plot.ly/' # Lien du topojson de la carte

# Voir pour config Css et autres styles
# Manque sous-titre de ggplot
# Problème de positionnement de la légende et de taille du graphique en html
# Problème de police de caratères (DejaVuSans non reconnu, ajouter Arial Narrow à la liste de font-family)

# CSS : agrandir la barre d'outils ?
# Entourer la barre d'outils ou les outils de jaune ?
# Attention au "dragmode" qui par défut est sur "zoom", il faut le mettre sur "pan" dans le layout

# ggplotly(): permet de transformer un plot de ggplot en objet plotly                      
# ToWebGL() : améliore la performance quand il y a de nombreux points
# https://plotly-r.com/performance.html

# Tooltips
# https://plotly-r.com/controlling-tooltips.html#tooltip-text-ggplotly

# Save
# https://plotly-r.com/saving.html

# Css pour Plotly----------------------------------------------------------------
# cssMod<-".modebar-btn {
#   border: 5px solid #ffff00 !important
# }
# 
# svg{
#   height: 1em;
#   width: 1em;
# }"
# 
# htmlMod <- htmltools::tags$style(type = "text/css",cssMod )

# Le code fonctionne mais il empêche les données de s'afficher
# A améliorer

# Fonction pour vérifier si l'on peut compresser un fichier plotly en limitant les dépendances externes nécessaires
# https://plotly-r.com/saving.html
# Fonction pour voir si cela vaut la peine d'utiliser partial_bundle
widget_file_size <- function(p) {
  d <- tempdir()
  withr::with_dir(d, htmlwidgets::saveWidget(p, "index.html"))
  f <- file.path(d, "index.html")
  mb <- round(file.info(f)$size / 1e6, 3)
  message("File is: ", mb," MB")
}

# Schema d'appel de la fonction
# widget_file_size(p)
# widget_file_size(partial_bundle(p))



##TRADEVE AIRES URBAINES----------------------------------------------------------------------------
#---------------------------------------------------------------------------------------------------
## Histogramme : Tradeve Europe Surfaces et nombre d'entrées en 1961 (racine carrée)------------------------------
Titre1 <- "Nombre d'aires urbaines selon leurs surfaces"
SousTitre1 <- "Europe, 1961"
Titre_SousTitre1 <- paste0("<b>",Titre1,"</b>","<br>",SousTitre1 )

TraView1<-ggplot(TradeveLonger1961, aes(x = Surface,y = ..count..)) + 
  geom_histogram(fill="#ff1a75", bins =100)+
  guides(x = guide_axis(angle = 90, n.dodge = 1))+
  coord_cartesian(xlim = c(0, NA), ylim = c(0, NA))+
  scale_x_sqrt (n.breaks = 20)+
  scale_y_sqrt (n.breaks = 16)+
  labs(
    x = "Surfaces (km2, échelle racine carrée)",
    y = "Nombre (échelle racine carrée)",
    title = Titre1,
    subtitle = SousTitre1,
    caption=SourceTradeve)+
  ThemeFunction # Theme prédéfini plus haut

# Ajouter axes
TraView1 <- AxesXY(TraView1)

# Afficher
TraView1

# Imprimer
# ImprimerPng(TraView1, "TraView1")
# ImprimerTiff(TraView1, "TraView1")

# PLOTLY EXPORT
# S'assurer que les valeurs des axes en x seront bien affichées à 90° dans le htmlwidget
TraView1<- TraView1+
theme(axis.text.x = element_text(angle = 90))+
  annotate(geom="text",
           label=SourceTradeve,
           hjust= 1,
           vjust=-0.1,
           size=4)

TraView1

# Produire le htmlwdiget
# Tootip avec deux chiffres après la virgule > withr::with_options(list(digits=3)
# Choix des variables dans le tooltip > ggplotly(TraView1, tooltip = "Surface")
# Appel de la fonction de configuration définie plus haut pour l'interface de plotly > ConfigPlotly1()%>%
# S'assurer que par défaut, on peut naviguer en mode pan dans le graphique > dragmode="pan"
# Compléter le titre avec le sous-titre (non pris en compte dans plotly) et l'aligner correctement
# https://datascott.com/blog/subtitles-with-ggplotly/
# Ajouter la source du graphique 
# https://stackoverflow.com/questions/45103559/plotly-adding-a-source-or-caption-to-a-chart

TraView1plotly <- withr::with_options(list(digits=3,scipen = 20),ggplotly(TraView1))%>%
  ConfigPlotly1()%>%
  layout(dragmode="pan",
         margin=list(t=100,
                     r=80,
                     b=100,
                     l=80),
         title=list(text=Titre_SousTitre1,
                    xanchor='left',
                    yanchor='top'),
         annotations = list(x = 1, 
                            y = 0,
                            text = SourceTradeve,
                            showarrow = F,
                            xref='paper',
                            yref='paper',
                            xanchor='right',
                            yanchor='bottom',
                            yshift ='-90',
                            font=list(size=15)))
TraView1plotly

# PROBLEME A REGLER : les tooltips ne donnent pas la bonne valeur d'affichage avec un des échelles d'affichage des axes à la racine carrée
# Il semble que plotly calcule la valeur d'affichage et pas la valeur calculée

# Réduire taille du html widget (permet de n'associer au graphique que les dépendances qui sont strictement nécessaires à son fonctionnement)
TraView1plotly<- partial_bundle(TraView1plotly)

# Enregistrer le graphique
# https://plotly-r.com/saving.html
# si l'on n'a qu'un seule graphique interactif, il est intéressant de le mettre en "self-contained" ce qui évite d'avoir des fichiers joints
# Mais lorsque l'on pense héberger tous ses graphiques dans le même dossier sur le web, on a intérêt à mettre en commun les dépendances pour limiter le poids des fichiers
# Cette approche permet aussi d'afficher plusieurs graphiques interactifs sur une page web en améliorant les performance de calcul et donc d'affichage

# Améliorer le caractère "responsive" du htmlwidget lorsqu'il est embarqué dans un iframe sur une page web
# https://bhaskarvk.github.io/widgetframe/

saveWidget(frameableWidget(TraView1plotly), "./03-Output_figures/TraView1plotly.html", selfcontained = FALSE, libdir = "HTML_dependencies")

## Histogramme : Tradeve Europe Populations 1961 et 2011, nombre d'entrées (racine carrée)------------------------------
Titre2 <- "Nombre d'aires urbaines selon leurs populations"
SousTitre2 <- "Europe, entre 1961 et 2011"
Titre_SousTitre2 <- paste0("<b>",Titre2,"</b>","<br>",SousTitre2 )

MedianePop1961<- median(TradeveLonger1961$Population, na.rm = TRUE)
MedianePop2011<- median(TradeveLonger2011$Population, na.rm = TRUE)

TraView2<- ggplot(TradeveLonger1961_2011, aes(x=Population,color=Annee)) +
  geom_histogram(fill="white", bins =100, alpha=0, position="identity", size=1)+
  coord_cartesian(xlim = c(0, NA), ylim = c(0, NA))+
  scale_color_manual(values = c(`1961` = "#FF1A75",`2011` = "#00A6A6")) +
  guides(x = guide_axis(angle = 90, n.dodge = 1))+
  scale_x_sqrt (n.breaks = 20)+
  scale_y_sqrt (n.breaks = 20)+
  labs(
    x = "Population (hab, échelle racine carrée)",
    y = "Nombre (échelle racine carrée)",
    title = Titre2,
    subtitle = SousTitre2,
    caption=SourceTradeve,
    color = "Années")+
  ThemeFunction

TraView2 <- AxesXY(TraView2)+
  geom_vline (aes(xintercept=MedianePop2011), linetype="dashed", color="#00a6a6", size=1.2)+
  geom_vline (aes(xintercept=MedianePop1961), linetype="dashed", color="#FF1A75", size=1.2)+
  annotate("text",
           x=(MedianePop2011+100000),
           y=1050,
           label="Médiane 2011",
           color="#00a6a6")+
  annotate("text",
           x=(MedianePop1961+110000),
           y=1100,
           label="Médiane 1961",
           color="#FF1A75")

TraView2

ImprimerPng(TraView2, "01_Europe_Nb_Metro_Population")
ImprimerTiff(TraView2, "01_Europe_Nb_Metro_Population")

TraView2<- TraView2+
  theme(axis.text.x = element_text(angle = 90))

TraView2plotly <- withr::with_options(list(digits=1,scipen = 20),ggplotly(TraView2))%>%
  ConfigPlotly1()%>%
  layout(dragmode="pan",
         margin=list(t=100,
                     r=80,
                     b=100,
                     l=80),
         title=list(text=Titre_SousTitre2,
                    xanchor='left',
                    yanchor='top'),
         annotations = list(x = 1, 
                            y = 0,
                            text = SourceTradeve,
                            showarrow = F,
                            xref='paper',
                            yref='paper',
                            xanchor='right',
                            yanchor='bottom',
                            yshift ='-90',
                            font=list(size=15)))


TraView2plotly

TraView2plotly<- partial_bundle(TraView1plotly2)

saveWidget(frameableWidget(TraView2plotly), "./03-Output_figures/TraView2plotly.html", selfcontained = FALSE, libdir = "HTML_dependencies")


## Histogramme : Tradeve Europe surfaces 1961 et 2011, nombre d'entrées (racine carrée)------------------------------
Titre3 <- "Nombre d'aires urbaines selon leurs surfaces"
SousTitre3 <- "Europe, entre 1961 et 2011"
Titre_SousTitre3 <- paste0("<b>",Titre3,"</b>","<br>",SousTitre3 )

MedianeSurf1961<-median(TradeveLonger1961$Surface, na.rm = TRUE)
MedianeSurf2011<-median(TradeveLonger2011$Surface, na.rm = TRUE)
MedianeSurf1961
MedianeSurf2011

TraView3 <- ggplot(TradeveLonger1961_2011, aes(x=Surface,color=Annee)) +
  geom_histogram(fill="white", bins =100, alpha=0, position="identity", size=1)+
  scale_color_manual(values = c(`1961` = "#FF1A75",`2011` = "#00A6A6")) +
  coord_cartesian(xlim = c(0, NA), ylim = c(0, NA))+
  guides(x = guide_axis(angle = 90, n.dodge = 1))+
  scale_x_sqrt (n.breaks = 20)+
  scale_y_sqrt (n.breaks = 16)+
  labs(
    x = "Surface (km2, échelle racine carrée)",
    y = "Nombre (échelle racine carrée)",
    title = Titre3,
    subtitle = SousTitre3,
    caption=SourceTradeve,
    color = "Années")+
  ThemeFunction

TraView3 <- AxesXY(TraView3)+
  geom_vline (aes(xintercept=MedianeSurf2011), linetype="dashed", color="#00a6a6", size=1.2)+
  geom_vline (aes(xintercept=MedianeSurf1961), linetype="dashed", color="#FF1A75", size=1.2)+
  annotate("text",
           x=(MedianeSurf2011+200),
           y=650,
           label="Médiane 2011",
           color="#00a6a6")+
  annotate("text",
           x=(MedianeSurf1961+200),
           y=680,
           label="Médiane 1961",
           color="#FF1A75")

TraView3

ImprimerPng(TraView3, "02_Europe_Nb_Metro_Surface")
ImprimerTiff(TraView3, "02_Europe_Nb_Metro_Surface")

TraView3<- TraView3+
  theme(axis.text.x = element_text(angle = 90))

TraView3plotly <- withr::with_options(list(digits=3,scipen = 20),ggplotly(TraView3))%>%
  ConfigPlotly1()%>%
  layout(dragmode="pan",
         margin=list(t=100,
                     r=80,
                     b=100,
                     l=80),
         title=list(text=Titre_SousTitre3,
                    xanchor='left',
                    yanchor='top'),
         annotations = list(x = 1, 
                            y = 0,
                            text = SourceTradeve,
                            showarrow = F,
                            xref='paper',
                            yref='paper',
                            xanchor='right',
                            yanchor='bottom',
                            yshift ='-90',
                            font=list(size=15)))

TraView3plotly

## -------------------------------------------------------------------------------------------------
## Histogramme : Tradeve Europe densité de Population 1961 et 2011, nombre d'entrées (racine carrée)------------------------------
Titre4 <- "Nombre d'aires urbaines selon leurs densités de population"
SousTitre4 <- "Europe, entre 1961 et 2011"
Titre_SousTitre4 <- paste0("<b>",Titre4,"</b>","<br>",SousTitre4 )

MedianeDens1961<-median(TradeveLonger1961$Densite,na.rm = TRUE)
MedianeDens2011<-median(TradeveLonger2011$Densite,na.rm = TRUE)

MedianeDens1961
MedianeDens2011

TraView4 <- ggplot(TradeveLonger1961_2011, aes(x=Densite,color=Annee)) +
  geom_histogram(fill="white", bins =100, alpha=0, position="identity", size=1)+
  scale_color_manual(values = c(`1961` = "#FF1A75",`2011` = "#00A6A6")) +
  coord_cartesian(xlim = c(0, NA), ylim = c(0, NA))+
  guides(x = guide_axis(angle = 90, n.dodge = 1))+
  scale_x_sqrt (n.breaks = 20)+
  scale_y_sqrt (n.breaks = 16)+
  labs(
    x = "Densité de Population (hab/km2, échelle racine carrée)",
    y = "Nombre (échelle racine carrée)",
    title = Titre4,
    subtitle = SousTitre4,
    caption=SourceTradeve,
    color = "Années")+
  ThemeFunction

TraView4 <- AxesXY(TraView4)+
  geom_vline (aes(xintercept=MedianeDens2011), linetype="dashed", color="#00a6a6", size=1.2)+
  geom_vline (aes(xintercept=MedianeDens1961), linetype="dashed", color="#FF1A75", size=1.2)+
  annotate("text",
           x=(MedianeDens2011+270),
           y=230,
           label="Médiane 2011",
           color="#00a6a6")+
  annotate("text",
           x=(MedianeDens1961-170),
           y=230,
           label="Médiane 1961",
           color="#FF1A75")

TraView4

ImprimerPng(TraView4, "04_Europe_Nb_Metro_Densite")
ImprimerTiff(TraView4, "04_Europe_Nb_Metro_Densite")

TraView4<- TraView4+
  theme(axis.text.x = element_text(angle = 90))

TraView4plotly <- withr::with_options(list(digits=3,scipen = 20),ggplotly(TraView4))%>%
  ConfigPlotly1()%>%
  layout(dragmode="pan",
         margin=list(t=100,
                     r=80,
                     b=100,
                     l=80),
         title=list(text=Titre_SousTitre4,
                    xanchor='left',
                    yanchor='top'),
         annotations = list(x = 1, 
                            y = 0,
                            text = SourceTradeve,
                            showarrow = F,
                            xref='paper',
                            yref='paper',
                            xanchor='right',
                            yanchor='bottom',
                            yshift ='-90',
                            font=list(size=15)))

TraView4plotly

## -------------------------------------------------------------------------------------------------
## Histogramme : Tradeve Europe Populations et nombre d'entrées (racine carrée) avec valeur médiane------------------------------
Titre5 <- "Nombre d'aires urbaines selon leurs populations"
SousTitre5 <- "Europe, 2011"
Titre_SousTitre5 <- paste0("<b>",Titre5,"</b>","<br>",SousTitre5)

MedianePop2011<- median(TradeveLonger2011$Population, na.rm = TRUE)

TraView5 <- ggplot(TradeveLonger2011, aes(x = Population,y = ..count..)) +
  geom_histogram(fill="#ff1a75", bins =20)+
  guides(x = guide_axis(angle = 90, n.dodge = 1))+
  coord_cartesian(xlim = c(0, NA), ylim = c(0, 3100))+
  scale_x_sqrt (n.breaks = 20)+
  scale_y_sqrt (n.breaks = 20)+
  labs(
    x = "Population (hab, échelle racine carrée)",
    y = "Nombre (échelle racine carrée)",
    title = Titre5,
    subtitle = SousTitre5,
    caption=SourceTradeve)+
  ThemeFunction

TraView5 <- AxesXY(TraView5)+
  geom_vline(aes(xintercept=MedianePop2011), linetype="dashed", color="#00a6a6", size=1.2)+ 
  annotate("text",
         x=(MedianePop2011+50000),
         y=3300,
         label="Médiane",
         color="#00a6a6",)

TraView5

# ImprimerPng(TraView5, "02_Europe_Nb_Metro_Surface_2011")
# ImprimerTiff(TraView5, "02_Europe_Nb_Metro_Surface_2011")

TraView5<- TraView5+
  theme(axis.text.x = element_text(angle = 90))

TraView5plotly <- withr::with_options(list(digits=1,scipen = 20),ggplotly(TraView5, tooltip = "Population"))%>%
  ConfigPlotly1()%>%
  layout(dragmode="pan",
         margin=list(t=100,
                     r=80,
                     b=100,
                     l=80),
         title=list(text=Titre_SousTitre5,
                    xanchor='left',
                    yanchor='top'),
         annotations = list(x = 1, 
                            y = 0,
                            text = SourceTradeve,
                            showarrow = F,
                            xref='paper',
                            yref='paper',
                            xanchor='right',
                            yanchor='bottom',
                            yshift ='-90',
                            font=list(size=15)))

TraView5plotly

## Histogramme : Tradeve France Populations 1961 et 2011, nombre d'entrées (racine carrée)------------------------------
Titre6 <- "Nombre d'aires urbaines selon leurs populations"
SousTitre6 <- "France, entre 1961 et 2011"
Titre_SousTitre6 <- paste0("<b>",Titre6,"</b>","<br>",SousTitre6)

MedianePopFR1961<- median(TradeveLongerFR1961$Population, na.rm = TRUE)
MedianePopFR2011<- median(TradeveLongerFR2011$Population, na.rm = TRUE)

MedianePopFR1961
MedianePopFR2011

TraView6 <- ggplot(TradeveLongerFR1961_2011, aes(x=Population,color=Annee)) +
  geom_histogram(fill="white", bins =100, alpha=0, position="identity", size=1)+
  scale_color_manual(values = c(`1961` = "#FF1A75",`2011` = "#00A6A6")) +
  coord_cartesian(xlim = c(0, NA), ylim = c(0.2, NA))+
  guides(x = guide_axis(angle = 90, n.dodge = 1))+
  scale_x_sqrt (n.breaks = 20)+
  scale_y_sqrt (n.breaks = 32)+
  labs(
    x = "Population (hab, échelle racine carrée)",
    y = "Nombre (échelle racine carrée)",
    title = Titre6,
    subtitle = SousTitre6,
    caption=SourceTradeve,
    color = "Années")+
  ThemeFunction

TraView6 <- AxesXY(TraView6)+
  geom_vline (aes(xintercept=MedianePopFR1961), linetype="dashed", color="#00a6a6", size=1.2)+
  geom_vline (aes(xintercept=MedianePopFR2011), linetype="dashed", color="#FF1A75", size=1.2)+
  annotate("text",
           x=(MedianePop2011+90000),
           y=120,
           label="Médiane 2011",
           color="#00a6a6")+
  annotate("text",
           x=(MedianePop1961+100000),
           y=125,
           label="Médiane 1961",
           color="#FF1A75")

TraView6

ImprimerPng(TraView6, "01_France_Nb_Metro_Population")
ImprimerTiff(TraView6, "01_France_Nb_Metro_Population")

TraView6<- TraView6+
  theme(axis.text.x = element_text(angle = 90))

TraView6plotly <- withr::with_options(list(digits=1,scipen = 20),ggplotly(TraView6, tooltip = "Population"))%>%
  ConfigPlotly1()%>%
  layout(dragmode="pan",
         margin=list(t=100,
                     r=80,
                     b=100,
                     l=80),
         title=list(text=Titre_SousTitre6,
                    xanchor='left',
                    yanchor='top'),
         annotations = list(x = 1, 
                            y = 0,
                            text = SourceTradeve,
                            showarrow = F,
                            xref='paper',
                            yref='paper',
                            xanchor='right',
                            yanchor='bottom',
                            yshift ='-90',
                            font=list(size=15)))

TraView6plotly

## Histogramme : Tradeve France surfaces 1961 et 2011, nombre d'entrées (racine carrée)------------------------------
Titre7 <- "Nombre d'aires urbaines selon leurs surfaces"
SousTitre7 <- "France, entre 1961 et 2011"
Titre_SousTitre7 <- paste0("<b>",Titre7,"</b>","<br>",SousTitre7)

MedianeSurfFR1961<-median(TradeveLongerFR1961$Surface,na.rm = TRUE)
MedianeSurfFR2011<-median(TradeveLongerFR2011$Surface,na.rm = TRUE)

TraView7<- ggplot(TradeveLongerFR1961_2011, aes(x=Surface,color=Annee)) +
  geom_histogram(fill="white", bins =100, alpha=0, position="identity", size=1)+
  scale_color_manual(values = c(`1961` = "#FF1A75",`2011` = "#00A6A6")) +
  coord_cartesian(xlim = c(0, NA), ylim = c(0, NA))+
  guides(x = guide_axis(angle = 90, n.dodge = 1))+
  scale_x_sqrt (n.breaks = 40)+
  scale_y_sqrt (n.breaks = 32)+
  labs(
    x = "Surface (km2, échelle racine carrée)",
    y = "Nombre (échelle racine carrée)",
    title = Titre7,
    subtitle = SousTitre7,
    caption=SourceTradeve,
    color = "Années")+
  ThemeFunction

TraView7 <- AxesXY(TraView7)+
  geom_vline (aes(xintercept=MedianeSurfFR2011), linetype="dashed", color="#00a6a6", size=1.2)+
  geom_vline (aes(xintercept=MedianeSurfFR1961), linetype="dashed", color="#FF1A75", size=1.2)+
  annotate("text",
           x=(MedianeSurfFR2011+50),
           y=45,
           label="Médiane 2011",
           color="#00a6a6")+
  annotate("text",
           x=(MedianeSurfFR1961-35),
           y=45,
           label="Médiane 1961",
           color="#FF1A75")

# Remarque annotations: pour tourner les textes, mettre "angle=90"

TraView7

ImprimerPng(TraView7, "02_France_Nb_Metro_Surface")
ImprimerTiff(TraView7, "02_France_Nb_Metro_Surface")

TraView7<- TraView7+
  theme(axis.text.x = element_text(angle = 90))

TraView7plotly <- withr::with_options(list(digits=1,scipen = 20),ggplotly(TraView7, tooltip = "Population"))%>%
  ConfigPlotly1()%>%
  layout(dragmode="pan",
         margin=list(t=100,
                     r=80,
                     b=100,
                     l=80),
         title=list(text=Titre_SousTitre7,
                    xanchor='left',
                    yanchor='top'),
         annotations = list(x = 1, 
                            y = 0,
                            text = SourceTradeve,
                            showarrow = F,
                            xref='paper',
                            yref='paper',
                            xanchor='right',
                            yanchor='bottom',
                            yshift ='-90',
                            font=list(size=15)))

TraView7plotly

## Histogramme : Tradeve augmentation de la densité de population (1961-2011) et nombre d'entrées (racine carrée)------------------------------
Titre8 <- "Nombre d'aires urbaines selon l'augmentation annuelle de leur densité de population"
SousTitre8 <- "Europe, entre 1961 et 2011"
Titre_SousTitre8 <- paste0("<b>",Titre8,"</b>","<br>",SousTitre8)

TraView8<- ggplot(Tradeve, aes(x = DA2011_1961,y = ..count..)) + 
  geom_histogram(fill="#ff1a75", bins =100)+
  coord_cartesian(xlim = c(-75, 125), ylim = c(1.5, NA))+
  scale_y_sqrt (n.breaks = 40)+
  scale_x_continuous (n.breaks = 10)+
  guides(x = guide_axis(angle = 90, n.dodge = 1))+
  labs(
    x = "Augmentation annuelle de la densité de population (hab/km2) entre 1961 et 2011",
    y = "Nombre (échelle racine carrée)",
    title = Titre8,
    subtitle = SousTitre8,
    caption=SourceTradeve)+
  ThemeFunction

TraView8 <- AxesXY(TraView8)+
  geom_vline(aes(xintercept=median(Tradeve$DA2011_1961,na.rm = TRUE)), linetype="dashed", color="#00a6a6", size=1)+
  annotate("text",
           x=median(Tradeve$DA2011_1961,na.rm = TRUE)+11,
           y=875,
           label="Médiane 2011",
           color="#00a6a6")
  

TraView8

ImprimerPng(TraView8, "03_Europe_Nb_Metro_Surface_VAR")
ImprimerTiff(TraView8, "03_Europe_Nb_Metro_Surface_VAR")


# ggplotly(TraView8)

## Diagramme de points : Tradeve surfaces et augmentation de la densité de population (racine carrée) -----------------------
Titre9 <- "Relation entre surface de l'aire urbaine et variation de la densité de population"
SousTitre9 <- "Europe, entre 1961 et 2011"
Titre_SousTitre9 <- paste0("<b>",Titre9,"</b>","<br>",SousTitre9)
# Etiquette9<- "Nom : (%{label}) <br> Surface : (%{x}) <br> Augmentation densité : (%{y})" for hovertemplate # Ou le mettre ?

MedianeDa2011_1961<- median(TradeveLonger1961$DA2011_1961,na.rm = TRUE)

TraView9<- ggplot(TradeveLonger1961)+
  aes(x =Surface,
      y = DA2011_1961,
      text = paste0("Augmentation densité: ", TradeveLonger1961$DA2011_1961),
      label= Nom)+ 
  geom_point(color="#ff1a75",alpha=0.5, size=5)+
  scale_x_sqrt (n.breaks = 40)+
  scale_y_continuous (n.breaks = 20)+
  guides(x = guide_axis(angle = 90, n.dodge = 1))+
  labs(
    x = "Surfaces en 1961 (km2, échelle racine carrée)",
    y = "Augmentation annuelle de la densité de population (hab/km2) entre 1961 et 2011",
    title = Titre9,
    subtitle = SousTitre9,
    caption=SourceTradeve)+
  ThemeFunction2
TraView9

                    
TraView9 <- AxesXY(TraView9)+
  geom_hline(aes(yintercept=MedianeDa2011_1961),
             linetype="dashed",
             color="#00a6a6",
             size=1)+
  annotate("text",
           x=20000,
           y=(MedianeDa2011_1961+2),
           label="Médiane",
           color="#00a6a6")

TraView9

ImprimerPng(TraView9, "04_Europe_Surface_Densité")
ImprimerTiff(TraView9, "04_Europe_Surface_Densité")


# Produire le htmlwdiget avec plotly
TraView9<- TraView9+
  theme(axis.text.x = element_text(angle = 90))

TraView9plotly<- withr::with_options(list(digits=3,scipen = 20),toWebGL(ggplotly(TraView9,tooltip = c("x", "text", "label"))))%>%
  ConfigPlotly1()%>%
  layout(dragmode="pan",
         margin=list(t=100,
                     r=80,
                     b=100,
                     l=80),
         title=list(text=Titre_SousTitre9,
                    xanchor='left',
                    yanchor='top'),
         annotations = list(x = 1, 
                            y = 0,
                            text = SourceTradeve,
                            showarrow = F,
                            xref='paper',
                            yref='paper',
                            xanchor='right',
                            yanchor='bottom',
                            yshift ='-90',
                            font=list(size=15)))


TraView9plotly

# Réduire taille du html widget (permet de n'associer au graphique que ce qui est strictement nécessaire à son fonctionnement)
TraView9plotly<- partial_bundle(TraView9plotly)

# Enregistrer le graphique
saveWidget(frameableWidget(TraView9plotly), "./03-Output_figures/04_Europe_Surface_Densité.html", selfcontained = FALSE, libdir = "HTML_dependencies")



## Diagramme de points : Tradeve population et augmentation de la densité de population (racine carrée) 1961-2011 -----------------------
Titre10 <- "Relation entre population de l'aire urbaine et variation de la densité de population"
SousTitre10 <- "Europe, entre 1961 et 2011"
Titre_SousTitre10 <- paste0("<b>",Titre10,"</b>","<br>",SousTitre10)

TraView10<- ggplot(TradeveLonger1961)+
  aes(x =Population,
      y = DA2011_1961,
      text = paste0("Augmentation densité: ", TradeveLonger1961$DA2011_1961),
      label= Nom)+ 
  geom_point(color="#ff1a75",alpha=0.5, size=5)+
  scale_x_sqrt (n.breaks = 20)+
  scale_y_continuous (n.breaks = 20)+
  guides(x = guide_axis(angle = 90, n.dodge = 1))+
  labs(
    x = "Population en 1961 (hab, échelle racine carrée)",
    y = "Augmentation annuelle de la densité de population (hab/km2, 1961-2011)",
    title = Titre10,
    subtitle = SousTitre10,
    caption=SourceTradeve)+
  ThemeFunction2

TraView10 <- AxesXY(TraView10)+
  geom_hline(aes(yintercept=MedianeDa2011_1961),
             linetype="dashed",
             color="#00a6a6",
             size=1)+
  annotate("text",
           x=8000000,
           y=(MedianeDa2011_1961+2),
           label="Médiane",
           color="#00a6a6")

TraView10

ImprimerPng(TraView10, "05_Europe_Population_Densité")
ImprimerTiff(TraView10, "05_Europe_Population_Densité")

# Produire le htmlwdiget avec plotly
TraView10<- TraView10+
  theme(axis.text.x = element_text(angle = 90))


TraView10plotly<- withr::with_options(list(digits=3,scipen = 20),toWebGL(ggplotly(TraView10,tooltip = c("x", "text", "label"))))%>%
  ConfigPlotly1()%>%
  layout(dragmode="pan",
         margin=list(t=100,
                     r=80,
                     b=100,
                     l=80),
         title=list(text=Titre_SousTitre10,
                    xanchor='left',
                    yanchor='top'),
         annotations = list(x = 1, 
                            y = 0,
                            text = SourceTradeve,
                            showarrow = F,
                            xref='paper',
                            yref='paper',
                            xanchor='right',
                            yanchor='bottom',
                            yshift ='-90',
                            font=list(size=15)))

TraView10plotly

# Réduire taille du html widget (permet de n'associer au graphique que ce qui est strictement nécessaire à son fonctionnement)
TraView10plotly<- partial_bundle(TraView10plotly)

# Enregistrer le graphique
saveWidget(frameableWidget(TraView10plotly), "./03-Output_figures/05_Europe_Population_Densité.html", selfcontained = FALSE, libdir = "HTML_dependencies")

## Diagramme de points : Tradeve surfaces et population (racine carrée, couleur densité) 2011-----------------------
Titre11 <- "Relation entre surface de l'aire urbaine et population"
SousTitre11 <- "Europe, 2011"
Titre_SousTitre11 <- paste0("<b>",Titre11,"</b>","<br>",SousTitre11)

# Geométrie pour carte
TradeveCarte2011 <- TradeveCarte2011%>%
  select(2,12,13)%>%
  rename(Longitude="X", Latitude="Y")

TradeveLonger2011Carte <- TradeveLonger2011%>%
  left_join(TradeveCarte2011)

# Highlight query dans plotly (côté client)
RechercherAireTradeve2011 <- highlight_key(TradeveLonger2011Carte, ~Nom, group ="<b>Sélectionner des aires urbaines Tradeve 2011</b>")

TraView11 <- ggplot(RechercherAireTradeve2011)+
  aes(x =Surface,
      y = Population,
      colour = DA2011_1961,
      text=paste0("Augmentation densité: ", DA2011_1961),
      label= Nom)+ 
  geom_point(size=5)+
  scale_color_viridis_c(option = "plasma", direction = 1) +
  scale_x_sqrt (n.breaks = 20)+
  scale_y_sqrt (n.breaks = 20)+
  guides(x = guide_axis(angle = 90, n.dodge = 1))+
  labs(x = "Surfaces en 2011 (km2, échelle racine carrée)",
    y = "Population en 2011 (hab, échelle racine carrée)",
    title = Titre11,
    subtitle = SousTitre11,
    caption=SourceTradeve,
    color = "Variation annuelle \ndensité de population\n(1961-2011, hab/km2)")+
  ThemeFunction2

TraView11 <- AxesXY(TraView11)

TraView11

ImprimerPng(TraView11, "06_Europe_Surface_Population_Densité")
ImprimerTiff(TraView11, "06_Europe_Surface_Population_Densité")

# Produire le htmlwdiget avec plotly
s <- attrs_selected(
  mode = "markers")


TraView11<- TraView11+
  theme(axis.text.x = element_text(angle = 90))


TraView11plotly<- withr::with_options(list(digits=3,scipen = 20),
                                      toWebGL(ggplotly(TraView11,
                                                       tooltip = c("x", "y","text", "label"))))

TraView11plotly

TraView11plotly<-TraView11plotly%>%
  highlight(on = "plotly_click",
            selectize = TRUE,
            persistent = TRUE,
            dynamic = FALSE,
            color = "#00A6A6",
            opacityDim=0.1,
            selected = s)

TraView11plotly<-TraView11plotly%>%
  ConfigPlotly1()%>%
  layout(dragmode="pan",
         margin=list(t=100,
                     r=0,
                     b=150,
                     l=0),
         title=list(text=Titre_SousTitre11,
                    xanchor='left',
                    yanchor='top'),
         annotations = list(x = 1, 
                            y = 0,
                            text = SourceTradeve,
                            showarrow = F,
                            xref='paper',
                            yref='paper',
                            xanchor='right',
                            yanchor='bottom',
                            yshift ='-90',
                            font=list(size=15)))

TraView11plotly

# Essai carte à affiner
# qquery <- highlight_key(TradeveLonger2011Carte)
# 
# p <- plot_ly(qquery, x = ~Surface, y = ~Population) %>%
#   add_markers(alpha = 0.5) %>%
#   highlight("plotly_selected", dynamic = TRUE)
# 
# map <- leaflet(qquery) %>%
#   addTiles() %>%
#   addCircles()
# 
# # persistent selection can be specified via options()
# withr::with_options(
#   list(persistent = TRUE),
#   crosstalk::bscols(widths = c(6, 6),
#                     p,
#                     map))

# Réduire taille du html widget (permet de n'associer au graphique que ce qui est strictement nécessaire à son fonctionnement)
# Voir aussi : https://stackoverflow.com/questions/66106182/saving-htmlwidget-with-links-to-html-dependencies-instead-of-embedding-them
TraView11plotly<- partial_bundle(TraView11plotly)

# Reste l'habillage css à faire pour cette partie
# style = "margin-left:100px; font-family : arial narrow"
# le style par défaut vient de HTML_dependencies> selectize.bootstrap3.css
# Voir si l'on peut ajouter un code css au widget quelque part (dans le header ?)
# https://rstudio.github.io/htmltools//reference/include.html
# includeCSS(path, ...) ?
# https://stackoverflow.com/questions/35720698/is-it-possible-to-include-custom-css-in-htmlwidgets-for-r-and-or-leafletr ?
# Cette méthode permettrait-elle de partager un code .css entre tous les graphiques générés ?
# Voir aussi : https://stackoverflow.com/questions/44159168/how-to-style-an-single-individual-selectinput-menu-in-r-shiny

# Plotlycss<- tags$head(tags$style(HTML('label{font-family:arial narrow}
# .selectize-dropdown, .selectize-input, .selectize-input input {
#     color: #333333;
#     font-family: arial narrow !important;
#     font-size: inherit;
#     line-height: 20px}')))
# 
# TraView11plotly <- browsable(tagList(list(
#   tags$head(
#   tags$style('.selectize-dropdown {font-family: arial narrow !important;}')),
#   TraView11plotly)))
# TraView11plotly
# Cela marche, mais cela fait sauter les valeurs width et height du widget du dessous, probablement parce que cela agit sur les deux widgets en même temps

# Enregistrer le graphique
saveWidget(frameableWidget(TraView11plotly), "./03-Output_figures/06_Europe_Surface_Population_Densité_2011.html", selfcontained = FALSE, libdir = "HTML_dependencies", title = "Europe_Surface_Population_Densité")


## Diagramme de textes : Tradeve surfaces et population(racine carrée, couleur densité) 2011-----------------------
Titre12 <- "Relation entre surface et population de l'aire urbaine"
SousTitre12 <- "Europe, 2011"
Titre_SousTitre12 <- paste0("<b>",Titre12,"</b>","<br>",SousTitre12)

TraView12 <- ggplot(TradeveLonger2011)+
  aes(x =Surface,y = Population, colour = DA2011_1961)+
  scale_color_viridis_c(option = "plasma", direction = 1) +
  geom_text(size=5, label=Tradeve$Name,hjust = 0, nudge_x = 0.2)+
  coord_cartesian(xlim = c(0, 23000), ylim = c(0, 11000000))+
  scale_x_sqrt (n.breaks = 20)+
  scale_y_sqrt (n.breaks = 20)+
  guides(x = guide_axis(angle = 90, n.dodge = 1))+
  labs(
    x = "Surfaces en 2011 (km2, échelle racine carrée)",
    y = "Population en 2011 (hab, échelle racine carrée)",
    title = Titre12,
    subtitle = SousTitre12,
    caption=SourceTradeve,
    color = "Variation annuelle \ndensité de population\n(1961-2011, hab/km2)")+
  ThemeFunction2


TraView12 <- AxesXY(TraView12)

TraView12

ImprimerPng(TraView12, "08_Population_Surface_2011")
ImprimerTiff(TraView12, "08_Population_Surface_2011")

# ggplotly(TraView12)

## Diagramme de textes : Tradeve surfaces et population(racine carrée, couleur densité) 1961-----------------------
Titre13 <- "Relation entre surface et population de l'aire urbaine"
SousTitre13 <- "Europe, 1961"
Titre_SousTitre13 <- paste0("<b>",Titre13,"</b>","<br>",SousTitre13)

TraView13<-ggplot(TradeveLonger1961)+
  aes(x =Surface,y = Population, colour = DA2011_1961)+
  scale_color_viridis_c(option = "plasma", direction = 1) +
  geom_text(size=5, label=Tradeve$Name,hjust = 0, nudge_x = 0.2)+
  coord_cartesian(xlim = c(0, 23000), ylim = c(0, 11000000))+
  scale_x_sqrt (n.breaks = 20)+
  scale_y_sqrt (n.breaks = 20)+
  guides(x = guide_axis(angle = 90, n.dodge = 1))+
  labs(
    x = "Surfaces en 1961 (km2, échelle racine carrée)",
    y = "Population en 1961 (hab, échelle racine carrée)",
    title = Titre13,
    subtitle = SousTitre13,
    caption=SourceTradeve,
    color = "Variation annuelle \ndensité de population\n(1961-2011, hab/km2)")+
  ThemeFunction2

TraView13 <- AxesXY(TraView13)

TraView13

ImprimerPng(TraView13, "07_Population_Surface_1961")
ImprimerTiff(TraView13, "07_Population_Surface_1961")

TraView13plotly<- toWebGL(ggplotly(TraView13))%>%
  ConfigPlotly1()%>%
  layout(dragmode="pan",
        title="<b>Relation entre surface et population de l'aire urbaine</b>, Europe, 1961")

TraView13plotly

## Diagramme de points : Tradeve surfaces et population,(racine carrée) 1961 -----------------------
Titre14 <- "Relation entre surface et population de l'aire urbaine"
SousTitre14 <- "Europe, 1961"
Titre_SousTitre14 <- paste0("<b>",Titre14,"</b>","<br>",SousTitre14)

TraView14 <- ggplot(TradeveLonger1961)+
  aes(y = Population,
    x =Surface,
    colour = DA2011_1961,
    text=paste0("Augmentation densité: ", DA2011_1961),
    label= Nom)+
  geom_point(size=5)+
  scale_color_viridis_c(option = "plasma", direction = 1, na.value="#000000") +
  scale_x_sqrt (n.breaks = 20)+
  scale_y_sqrt (n.breaks = 20)+
  labs(
    x = "Surfaces (km2, échelle racine carrée)",
    y = "Population (hab, échelle racine carrée)",
    title = Titre14,
    subtitle = SousTitre14,
    caption = SourceTradeve,
    color = "Variation annuelle \ndensité de population\n(1961-2011, hab/km2)")+
  ThemeFunction2

TraView14 <- AxesXY(TraView14)

TraView14

# Produire le htmlwdiget avec plotly
s <- attrs_selected(
  mode = "markers")


TraView14<- TraView14+
  theme(axis.text.x = element_text(angle = 90))


TraView14plotly<- withr::with_options(list(digits=3,scipen = 20),
                                      toWebGL(ggplotly(TraView14,
                                                       tooltip = c("x", "y","text", "label"))))

TraView14plotly

TraView14plotly<-TraView14plotly%>%
  highlight(on = "plotly_click",
            selectize = TRUE,
            persistent = TRUE,
            dynamic = FALSE,
            color = "#00A6A6",
            opacityDim=0.1,
            selected = s)

TraView14plotly<-TraView14plotly%>%
  ConfigPlotly1()%>%
  layout(dragmode="pan",
         margin=list(t=100,
                     r=0,
                     b=150,
                     l=0),
         title=list(text=Titre_SousTitre14,
                    xanchor='left',
                    yanchor='top'),
         annotations = list(x = 1, 
                            y = 0,
                            text = SourceTradeve,
                            showarrow = F,
                            xref='paper',
                            yref='paper',
                            xanchor='right',
                            yanchor='bottom',
                            yshift ='-90',
                            font=list(size=15)))

TraView14plotly

## Diagramme de points/textes : Tradeve surfaces et population, 1961, zoom-----------------------
Titre15 <- "Relation entre surface et population de l'aire urbaine"
SousTitre15 <- "Europe, 1961, extrait"
Titre_SousTitre15 <- paste0("<b>",Titre15,"</b>","<br>",SousTitre15)

TradeveZoom1 <- Tradeve%>%
  filter(Pop_1961>750000&Pop_1961<1710000)

TraView15<- ggplot(TradeveZoom1, aes(x =Area_1961,y = Pop_1961, colour = DA2011_1961,label=TradeveZoom1$Name))+ 
  scale_color_viridis_c(option = "plasma", direction = 1) +
  coord_cartesian(xlim = c(200, 1600), ylim = c(800000, 1710000))+
  geom_point(size=2)+
  geom_text_repel()+
  labs(
    x = "Surfaces (km2, échelle racine carrée)",
    y = "Population (hab, échelle racine carrée)",
    title = Titre15,
    subtitle = SousTitre15,
    caption = SourceTradeve,
    color = "Variation annuelle \ndensité de population\n(1961-2011, hab/km2)")+
  ThemeFunction2

TraView15 

ImprimerPdf(TraView15, "07_Population_Surface_1961_extrait")
ImprimerPng(TraView15, "07_Population_Surface_1961_extrait")
ImprimerTiff(TraView15, "07_Population_Surface_1961_extrait")

# voir ggiraph geom_text_repel_interactive()

## Diagramme de points/textes : Tradeve surfaces et population, 2011, zoom -----------------------
Titre16 <- "Relation entre surface et population de l'aire urbaine"
SousTitre16 <- "Europe, 2011, extrait"
Titre_SousTitre16 <- paste0("<b>",Titre16,"</b>","<br>",SousTitre16)

TradeveZoom2 <- Tradeve%>%
  filter(Pop_2011>750000&Pop_2011<1710000)%>%
  filter(Area_2011>200&Area_2011<1600)

TraView16<- ggplot(TradeveZoom2)+
  aes(x =Area_2011,y = Pop_2011, colour = DA2011_1961,label=TradeveZoom2$Name)+
  scale_color_viridis_c(option = "plasma", direction = 1) +
  geom_point(size=2)+
  geom_text_repel()+
  coord_cartesian(xlim = c(200, 1600), ylim = c(800000, 1700000))+
  labs(
    x = "Surfaces (km2, échelle racine carrée)",
    y = "Population (hab, échelle racine carrée)",
    title = Titre16,
    subtitle = SousTitre16,
    caption=SourceTradeve,
    color = "Variation annuelle densité de population\n(1961-2011, hab/km2)")+
  ThemeFunction2

TraView16

ImprimerPdf(TraView16, "08_Population_Surface_2011_extrait")
ImprimerPng(TraView16, "08_Population_Surface_2011_extrait")
ImprimerTiff(TraView16, "08_Population_Surface_2011_extrait")


## Diagramme de points : Tradeve surfaces et population,(racine carrée) de 1961 à 2011 (tranches 10 ans), slider-----------------------
# https://plotly-r.com/animating-views.html

Titre17 <- "Relation entre surface et population de l'aire urbaine"
SousTitre17 <- "Europe, de 1961 à 2011"
Titre_SousTitre17 <- paste0("<b>",Titre17,"</b>","<br>",SousTitre17)

TraView17 <- ggplot(TradeveLonger,
                    aes(y = Population,
                        x = Surface,
                        colour = DA2011_1961,
                        text=paste0("Augmentation densité: ", DA2011_1961),
                        label= Nom))+
  scale_color_viridis_c(option = "plasma", direction = 1, na.value=NA) +
  geom_point(aes(size=2,
             frame = Annee,
             ids= Nom))+
  scale_x_sqrt (n.breaks = 20)+
  scale_y_sqrt (n.breaks = 20)+
  labs(
    x = "Surfaces (km2, échelle racine carrée)",
    y = "Population (hab, échelle racine carrée)",
    title = Titre17,
    subtitle = SousTitre17,
    caption = SourceTradeve,
    color = "Variation annuelle \ndensité de population\n(1961-2011, hab/km2)")+
  ThemeFunction2

TraView17 <- AxesXY(TraView17)
TraView17


# Produire le htmlwdiget avec plotly
TraView17<- TraView17+
  theme(axis.text.x = element_text(angle = 90))


TraView17plotly<- withr::with_options(list(digits=3,scipen = 20),
                                      ggplotly(TraView17,
                                               tooltip = c("x", "y","text", "label")))

TraView17plotly

TraView17plotly<-TraView17plotly%>%
  ConfigPlotly1()%>%
  layout(dragmode="pan",
         margin=list(t=100,
                     r=0,
                     b=180,
                     l=0),
         title=list(text=Titre_SousTitre17,
                    xanchor='left',
                    yanchor='top'),
         annotations = list(x = 1, 
                            y = 0,
                            text = SourceTradeve,
                            showarrow = F,
                            xref='paper',
                            yref='paper',
                            xanchor='right',
                            yanchor='bottom',
                            yshift ='-160',
                            font=list(size=15)))

TraView17plotly<- partial_bundle(TraView17plotly)

# Enregistrer le graphique
saveWidget(frameableWidget(TraView17plotly), "./03-Output_figures/06_Europe_Surface_Population_Densité_1961-2011.html", selfcontained = FALSE, libdir = "HTML_dependencies", title = "Europe_Surface_Population_Densité")

## Diagramme de points/textes : Tradeve surfaces et population,(racine carrée) de 1961 à 2011 (tranches 10 ans), slider-----------------------
Titre18 <- "Relation entre surface et population de l'aire urbaine"
SousTitre18 <- "Europe, de 1961 à 2011"
Titre_SousTitre18 <- paste0("<b>",Titre18,"</b>","<br>",SousTitre18)

TraView18 <- ggplot(TradeveLonger,
                    aes(x = Surface,
                        y = Population,
                        colour = DA2011_1961,
                        text=paste0("Augmentation densité: ", DA2011_1961),
                        label= Nom,
                        frame = Annee,
                        ids= ID_UMZ))+
  geom_point(size=3)+
  scale_color_viridis_c(option = "plasma", direction = 1, na.value=NA) +
  scale_x_sqrt (n.breaks = 20)+
  scale_y_sqrt (n.breaks = 20)+
  labs(
    x = "Surfaces (km2, échelle racine carrée)",
    y = "Population (hab, échelle racine carrée)",
    title = Titre18,
    subtitle = SousTitre18,
    caption = SourceTradeve,
    color = "Variation annuelle \ndensité de population\n(1961-2011, hab/km2)")+
  ThemeFunction2

TraView18 <- AxesXY(TraView18)
TraView18


# Produire le htmlwdiget avec plotly
TraView18<- TraView18+
  theme(axis.text.x = element_text(angle = 90))


TraView18plotly<- withr::with_options(list(digits=3,scipen = 20),
                                      ggplotly(TraView18,
                                               tooltip = c("x", "y","text", "label")))

TraView18plotly

TraView18plotly<-TraView18plotly%>%
  ConfigPlotly1()%>%
  layout(dragmode="pan",
         margin=list(t=100,
                     r=0,
                     b=180,
                     l=0),
         title=list(text=Titre_SousTitre18,
                    xanchor='left',
                    yanchor='top'),
         annotations = list(x = 1, 
                            y = 0,
                            text = SourceTradeve,
                            showarrow = F,
                            xref='paper',
                            yref='paper',
                            xanchor='right',
                            yanchor='bottom',
                            yshift ='-160',
                            font=list(size=15)))

TraView18plotly

TraView18plotly<- partial_bundle(TraView18plotly)

# Enregistrer le graphique
saveWidget(frameableWidget(TraView18plotly), "./03-Output_figures/06_Europe_Surface_Population_Densité_Textes_1961-2011.html", selfcontained = FALSE, libdir = "HTML_dependencies", title = "Europe_Surface_Population_Densité")



## Diagramme de points/textes : Tradeve surfaces et population,(racine carrée) de 1961 à 2011, animation , zoom -----------------------
# https://gganimate.com/articles/gganimate.html

Titre19 <- "Relation entre surface et population de l'aire urbaine"
SousTitre19 <- "Europe, 1961-2011, extrait"
Titre_SousTitre19 <- paste0("<b>",Titre19,"</b>","<br>",SousTitre19)

TradeveLongerMod <- TradeveLonger%>%
  mutate(Annee=as.integer(Annee),
         .after = "ID_UMZ")

# Trouver les villes à sélectionner dans le jeu de données
# TradeveLongerZoom1 <- TradeveLongerMod%>%
#   filter(Annee==2011&between(Population,790000, 1710000)&between(Surface,200,1600)|
#            Annee==2001&between(Population,790000, 1710000)&between(Surface,200,1600)|
#            Annee==1991&between(Population,790000, 1710000)&between(Surface,200,1600)|
#            Annee==1981&between(Population,790000, 1710000)&between(Surface,200,1600)|
#            Annee==1971&between(Population,790000, 1710000)&between(Surface,200,1600)|
#            Annee==1961&between(Population,790000, 1710000)&between(Surface,200,1600))
# 
# unique(TradeveLongerZoom1$ID_UMZ)

TradeveLongerZoom1 <- TradeveLongerMod%>%
  filter(ID_UMZ=="85"|ID_UMZ=="164"|ID_UMZ=="254"|ID_UMZ=="456"|ID_UMZ=="506"|ID_UMZ=="659"|ID_UMZ=="766"|ID_UMZ=="975"|
  ID_UMZ=="1073"|ID_UMZ=="1120"|ID_UMZ=="1208"|ID_UMZ=="1442"|ID_UMZ =="1476"|ID_UMZ=="1729"|ID_UMZ=="1764"|
  ID_UMZ=="1898"|ID_UMZ=="2320"|ID_UMZ=="2455"|ID_UMZ=="2605"|ID_UMZ=="2678"|ID_UMZ=="2688"|ID_UMZ=="2698"|ID_UMZ=="2825"|
  ID_UMZ=="2931"|ID_UMZ=="3013"|ID_UMZ=="3161"|ID_UMZ=="3224"|ID_UMZ=="3281"|ID_UMZ=="3472"|ID_UMZ=="3768"|
  ID_UMZ== "3966"|ID_UMZ=="4026"|ID_UMZ=="4040"|ID_UMZ=="1724_1"|ID_UMZ=="2095_1"|ID_UMZ=="3238_1")

TraView19 <- ggplot(TradeveLongerZoom1,
                    aes(x = Surface,
                      y = Population,
                        colour = DA2011_1961,
                        text=paste0("Augmentation densité: ", DA2011_1961),
                        label= Nom,
                        frame = Annee,
                        ids= ID_UMZ))+
  geom_point(size=5)+
  geom_text(color="grey50", nudge_y = 12)+
  geom_path()+
  scale_color_viridis_c(option = "plasma", direction = 1, na.value=NA) +
  coord_cartesian(xlim = c(200, 1600), ylim = c(800000, 1700000))+
  scale_x_sqrt (n.breaks = 20)+
  scale_y_sqrt (n.breaks = 20)+
  labs(
    x = "Surfaces (km2, échelle racine carrée)",
    y = "Population (hab, échelle racine carrée)",
    title = Titre17,
    subtitle = SousTitre17,
    caption = SourceTradeve,
    color = "Variation annuelle \ndensité de population\n(1961-2011, hab/km2)")+
  ThemeFunction2

TraView19

# ggplotly(TraView17)
# Produire le htmlwdiget avec plotly
# 
# TraView19<- TraView19+
#   theme(axis.text.x = element_text(angle = 90))

TraView19plotly<- withr::with_options(list(digits=3,scipen = 20),
                                      ggplotly(TraView19,
                                               tooltip = c("x", "y","text")))


TraView19plotly<- TraView19plotly%>%
  animation_opts(
    frame = 2000,
    transition = 2000,
    easing = "linear",
    redraw = TRUE,
    mode = "immediate"
  )

TraView19plotly<-TraView19plotly%>%
  ConfigPlotly2()%>%
  layout(dragmode="zoom",
         margin=list(t=100,
                     r=0,
                     b=180,
                     l=0),
         title=list(text=Titre_SousTitre19,
                    xanchor='left',
                    yanchor='top'),
         annotations = list(x = 1, 
                            y = 0,
                            text = SourceTradeve,
                            showarrow = F,
                            xref='paper',
                            yref='paper',
                            xanchor='right',
                            yanchor='bottom',
                            yshift ='-160',
                            font=list(size=15)))

TraView19plotly

TraView19plotly<- partial_bundle(TraView19plotly)

TraView19plotly

# Enregistrer le graphique
saveWidget(frameableWidget(TraView19plotly), "./03-Output_figures/06_Europe_Surface_Population_Densité_1961-2011_Textes_extrait.html", selfcontained = FALSE, libdir = "HTML_dependencies", title = "Europe_Surface_Population_Densité")


##--------------------------------------------------------------------------------------------------
##LAU 2---------------------------------------------------------------------------------------------
#---------------------------------------------------------------------------------------------------
# Histogramme : LAU2 2011 Europe populations et nombre d'entrées (racine carrée)------------------------------
Titre20 <- "Nombre de LAU selon leur densité de population"
SousTitre20 <- "Europe, 2011"
Titre_SousTitre20 <- paste0("<b>",Titre20,"</b>","<br>",SousTitre20)

TraView20<- ggplot(LAUdata2011, aes(x = DENS_2011,y = ..count..)) + 
  geom_histogram(fill="#ff1a75", bins =100)+
  guides(x = guide_axis(angle = 90, n.dodge = 1))+
  coord_cartesian(xlim = c(0, NA), ylim = c(1.2, NA))+
  scale_x_sqrt (n.breaks = 20)+
  scale_y_sqrt (n.breaks = 16)+
  labs(
    x = "Densité de population (hab/km2, échelle racine carrée)",
    y = "Nombre (échelle racine carrée)",
    title = Titre20,
    subtitle = SousTitre20,
    caption="Calculs: NLG. Source : Eurostat, LAU2",
    color = "Variation annuelle \ndensité de population\n(1961-2011, hab/km2)")+
  ThemeFunction

TraView20 <- AxesXY(TraView20)

TraView20

TraView20plotly<- toWebGL(ggplotly(TraView20))%>%
  ConfigPlotly2()%>%
  layout(dragmode="pan",
         title="<b>Nombre de LAU selon leur densité de population</b>, Europe, 2011")

## Diagramme de points : LAU2 2011 surfaces et population-----------------------
Titre21 <- "Relation entre surface de la commune et population"
SousTitre21 <- "Europe, 2011"
Titre_SousTitre21 <- paste0("<b>",Titre21,"</b>","<br>",SousTitre21)

TraView18<- ggplot(LAUdata2011)+
  aes(x =AREA_KM2, y = POP_2011, color=DENS_2011, label=LAU_NAME)+
  scale_color_viridis_c(option = "plasma", direction = 1) +
  geom_point(size=2)+
  scale_x_sqrt (n.breaks = 20)+
  scale_y_sqrt (n.breaks = 20)+
  guides(x = guide_axis(angle = 90, n.dodge = 1))+
  labs(
    x = "Surfaces (km2)",
    y = "Population (hab)",
    title = Titre21,
    subtitle = SousTitre21,
    caption="Calculs: NLG. Source : Eurostat, LAU2",
    color = "Densité de population (hab/km2)")+
  ThemeFunction2

TraView21 <- AxesXY(TraView18)
TraView21

TraView21plotly<- toWebGL(ggplotly(TraView21))%>%
  ConfigPlotly1()%>%
  layout(dragmode="pan",
         title="<b>Relation entre surface de la commune et population</b>, Europe, 2011")

TraView21plotly

## Diagramme de textes : LAU2 2011 surfaces et population, zoom large-----------------------
Titre22 <- "Relation entre surface de l'aire urbaine et population"
SousTitre22 <- "Europe, 2011, extrait"
Titre_SousTitre22 <- paste0("<b>",Titre22,"</b>","<br>",SousTitre22)

ggplot(LAUdata2011)+
  aes(x =AREA_KM2, y = POP_2011, color=DENS_2011)+
  scale_color_viridis_c(option = "plasma", direction = 1) +
  geom_text(size=4, label=LAUdata2011$LAU_NAME,hjust = 0, nudge_x = 0.1)+
  coord_cartesian(xlim = c(0, 30), ylim = c(60000, NA))+
  labs(
    x = "Surfaces (km2)",
    y = "Population (hab)",
    title = Titre22,
    subtitle = SousTitre22,
    caption="Calculs: NLG. Source : Eurostat, LAU2",
    color = "Densité de population (hab/km2)")+
  ThemeFunction2

## Diagramme de points/textes : LAU2 2011 surfaces et population, zoom moyen-----------------------
Titre23 <- "Relation entre surface de l'aire urbaine et population"
SousTitre23 <- "Europe, 2011, extrait"
Titre_SousTitre23<- paste0("<b>",Titre23,"</b>","<br>",SousTitre23)

ggplot(LAUdata2011)+
  aes(x =AREA_KM2, y = POP_2011, color=DENS_2011)+
  scale_color_viridis_c(option = "plasma", direction = 1) +
  geom_point(size=2)+
  geom_text(size=5, label=LAUdata2011$LAU_NAME,hjust = 0, nudge_x = 0.1)+
  coord_cartesian(xlim = c(0, 30), ylim = c(60000, 300000))+
  labs(
    x = "Surfaces (km2)",
    y = "Population (hab)",
    title = Titre23,
    subtitle = SousTitre23,
    caption="Calculs: NLG. Source : Eurostat, LAU2",
    color = "Densité de population (hab/km2)")+
  ThemeFunction2

## Diagramme de points/textes : LAU2 2011 surfaces et population, 2011, zoom -----------------------
Titre24 <- "Relation entre surface de l'aire urbaine et population"
SousTitre24 <- "Europe, 2011, extrait"
Titre_SousTitre24<- paste0("<b>",Titre24,"</b>","<br>",SousTitre24)

ggplot(LAUdata2011)+
  aes(x =AREA_KM2, y = POP_2011, color=POP_2011)+
  scale_color_viridis_c(option = "plasma", direction = 1) +
  geom_point(size=2)+
  geom_text(size=5, label=LAUdata2011$LAU_NAME,hjust = 0, nudge_x = 0.1)+
  coord_cartesian(xlim = c(6, 24), ylim = c(75000, 155000))+
  labs(
    x = "Surfaces (km2, échelle racine carrée)",
    y = "Population (hab, échelle racine carrée)",
    title = Titre21,
    subtitle = SousTitre21,
    caption="Calculs: NLG. Source : Eurostat, LAU2",
    color = "Densité de population")+
  ThemeFunction2

#---------------------------------------------------------------------------------------------------
##LAU2 et TRADEVE-----------------------------------------------------------------------------------
#---------------------------------------------------------------------------------------------------
Titre25 <- "Relation entre surface de la commune et population"
SousTitre25 <- "Europe, aires urbaines Tradeve, 2011"
Titre_SousTitre25<- paste0("<b>",Titre25,"</b>","<br>",SousTitre25)

RechercherLau2011 <- highlight_key(LAUTRA2011, ~LAU_NAME, group ="<b>Sélectionner des communes urbaines européennes, 2011</b>")

Traview25<- ggplot(RechercherLau2011)+
  aes(x =AREA_KM2, y = POP, color=UMZ_DENS, text=LAU_NAME, label=UMZ_NAME)+
  scale_color_viridis_c(option = "plasma", direction = 1) +
  geom_point(size=2)+
  # geom_text(size=5, label=LAUdata2011$LAU_NAME,hjust = 0, nudge_x = 0.1)+
  coord_cartesian(xlim = c(6, 24), ylim = c(75000, 200000))+
  labs(
    x = "Surfaces (km2, échelle racine carrée)",
    y = "Population (hab, échelle racine carrée)",
    title = Titre23,
    subtitle = SousTitre23,
    caption="Calculs: NLG. Source : Eurostat, LAU2, Tradeve",
    color = "Densité de population \nde l'aire urbaine")+
  ThemeFunction2

Traview25

# Produire le htmlwdiget avec plotly
s <- attrs_selected(
  mode = "markers")

TraView25plotly<- withr::with_options(list(digits=3,scipen = 20),
                                      ggplotly(Traview25,
                                               tooltip = c("x", "y","text", "label")))

TraView25plotly

TraView25plotly<-TraView25plotly%>%
  highlight(on = "plotly_click",
            selectize = TRUE,
            persistent = TRUE,
            dynamic = FALSE,
            color = "#00A6A6",
            opacityDim=0.1,
            selected = s)

TraView25plotly<-TraView25plotly%>%
  ConfigPlotly1()%>%
  layout(dragmode="pan",
         margin=list(t=100,
                     r=0,
                     b=150,
                     l=0),
         title=list(text=Titre_SousTitre25,
                    xanchor='left',
                    yanchor='top'),
         annotations = list(x = 1, 
                            y = 0,
                            text = "Calculs: NLG. Source : Eurostat, LAU2, Tradeve",
                            showarrow = F,
                            xref='paper',
                            yref='paper',
                            xanchor='right',
                            yanchor='bottom',
                            yshift ='-90',
                            font=list(size=15)))

TraView25plotly
