ESVD

###1 ESVD
options(repos = "https://cloud.r-project.org")
install.packages("ggrepel")
## Installing package into 'C:/Users/thali/AppData/Local/R/win-library/4.2'
## (as 'lib' is unspecified)
## package 'ggrepel' successfully unpacked and MD5 sums checked
## Warning: cannot remove prior installation of package 'ggrepel'
## Warning in file.copy(savedcopy, lib, recursive = TRUE): problema al copiar
## C:\Users\thali\AppData\Local\R\win-library\4.2\00LOCK\ggrepel\libs\x64\ggrepel.dll
## a C:\Users\thali\AppData\Local\R\win-library\4.2\ggrepel\libs\x64\ggrepel.dll:
## Permission denied
## Warning: restored 'ggrepel'
## 
## The downloaded binary packages are in
##  C:\Users\thali\AppData\Local\Temp\RtmpQf2ffK\downloaded_packages
setwd("C:/Users/thali/OneDrive - Wageningen University & Research/Escritorio/MASTERS/13. 14. 15. Internship/TASKS/4. DUPLICATES AND HOTSPOTS")

data <- read.csv("C:/Users/thali/OneDrive - Wageningen University & Research/Escritorio/MASTERS/13. 14. 15. Internship/TASKS/4. DUPLICATES AND HOTSPOTS/ESVD MASTER 230616.xlsx - ESVD MASTER 230616.csv")

library(ggplot2)
library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
library(maps)
library(mapdata)
library(MASS)
## 
## Attaching package: 'MASS'
## The following object is masked from 'package:dplyr':
## 
##     select
##1A GEOGRAPHY

# Aggregate data by country
country_counts <- data %>%
  group_by(Country_Code) %>%
  summarise(count = n())
data_clean <- data[complete.cases(data$Longitude, data$Latitude), ]

# Load map data
world_map <- map_data("world")

# Plot the map with datapoints
ggplot(data = data_clean, aes(x = Longitude, y = Latitude)) +
  geom_polygon(data = world_map, aes(x = long, y = lat, group = group), fill = "#f2f2f2", color = "#cccccc", linewidth = 0.5) +
  geom_point(alpha = 0.5, size = 0.5, color = "darkgreen") +
  scale_alpha(range = c(0.1, 0.7)) +
  theme_minimal() +
  labs(title = "Geographical Distribution of ESVD Data", 
       subtitle = "Datapoints",
       caption = "Source: ESVD MASTER 230616") +
  theme(plot.title = element_text(size = 18, face = "bold", hjust = 0.5),
        plot.subtitle = element_text(size = 14, hjust = 0.5),
        plot.caption = element_text(size = 10, hjust = 0),
        axis.title = element_text(size = 12),
        axis.text = element_text(size = 10))

# Plot the map with heatmap
ggplot() +
  geom_polygon(data = world_map, aes(x = long, y = lat, group = group), fill = "darkgrey", color = "white") +  
  stat_density_2d(data = data_clean, aes(x = Longitude, y = Latitude, fill = after_stat(level)), geom = "polygon", alpha = 0.5) +  
  scale_fill_viridis_c(name = "Density") +  
  theme_minimal() +  
  labs(title = "Geographical Distribution of ESVD Data", 
       subtitle = "Density of Values",
       fill = "Density", 
       caption = "Source: ESVD MASTER 230616",
       x = "Longitude", y = "Latitude") +  
  theme(plot.title = element_text(size = 18, face = "bold", hjust = 0.5),
        plot.subtitle = element_text(size = 14, hjust = 0.5),
        plot.caption = element_text(size = 10, hjust = 0),
        legend.title = element_text(size = 12),
        legend.text = element_text(size = 10))

##1B BIOMES

library(dplyr)
library(tidyr)
library(ggplot2)

# Gather the specified columns into a new dataframe
gathered_data <- gather(data, key = "Column", value = "Biomess",
                        ESVD2.0_Biome_1:ESVD2.0_Biome_10)

# Filter out empty cells
gathered_data <- gathered_data[!is.na(gathered_data$Biomess) & gathered_data$Biomess != "", ]

# Reset row names
rownames(gathered_data) <- NULL

# Select only the "Biome" column
gathered_data <- gathered_data[c('Biomess')]

#FIX ERRORS
gathered_data <- gathered_data %>%
  mutate(Biomess = ifelse(Biomess == "Coastal systems biome", "Coastal systems", Biomess))
gathered_data <- gathered_data %>%
  separate_rows(Biomess, sep = "; ")
gathered_data <- gathered_data %>%
  mutate(Biomess = ifelse(Biomess == "Rivers and Lakes", "Rivers and lakes", Biomess))
gathered_data <- gathered_data %>%
  mutate(Biomess = ifelse(Biomess == "Temperate forests and woodland", "Temperate forest and woodland", Biomess))


# Count the frequency of each biome
biome_counts <- table(gathered_data$Biomess)

# Convert the counts to a data frame
biome_counts_df <- as.data.frame(biome_counts)
colnames(biome_counts_df) <- c("Biome", "Frequency")

desired_order <- c("Marine", "Coastal systems", "Inland wetlands", "Rivers and lakes",
                   "Tropical and subtropical forests", "Temperate forest and woodland", "Cold climate evergreen forest and woodland", "Shrubland and shrubby woodland",
                   "Rangelands and natural grasslands", "Desert and semi desert", "Polar and alpine systems", "Subterranean systems", 
                   "Intensive land use", "Anthropogenic systems", 
                   "Urban green and blue infrastructure")
biome_counts_df$Biome <- factor(biome_counts_df$Biome, levels = desired_order)
biome_counts_df <- biome_counts_df[order(match(biome_counts_df$Biome, desired_order)), ]
library(RColorBrewer)
library(viridis)
## Loading required package: viridisLite
## 
## Attaching package: 'viridis'
## The following object is masked from 'package:maps':
## 
##     unemp
library(ggthemes)
custom_palette <- viridis(23)

# Create the pie chart
pie_chart <- ggplot(biome_counts_df, aes(x = "", y = Frequency, fill = Biome)) +
  geom_bar(stat = "identity", width = 1) +
  coord_polar("y", start = 0.5) +
  theme_excel_new() +
  scale_fill_manual(values = custom_palette) +
  geom_text(aes(label = paste0(round((Frequency/sum(Frequency)) * 100, 1), "%"),
                x = 1.7),
            position = position_stack(vjust = 0.5),
            color = "black", size = 3, fontface = "bold") +
  theme(legend.position = "right",
        legend.title = element_text(size = 10, face = "bold"),
        plot.title = element_text(size = 14, face = "bold"),
        plot.subtitle = element_text(size = 12), 
        plot.caption = element_text(size = 8),
        panel.grid = element_blank()) +  # Remove grid lines
  labs(title = "Biome Distribution",
       subtitle = "ESVD2.0_Biome",
       caption = "Source: ESVD MASTER 230616")
# Print the modified pie chart
print(pie_chart)

#create radar chart
biome_counts_df <- biome_counts_df %>%
  mutate(Biome_Number = as.numeric(factor(Biome, levels = unique(Biome))))
biome_counts_df$Biome_Number <- as.factor(biome_counts_df$Biome_Number)
new_row <- data.frame(Biome = "Other", Frequency = 0, Biome_Number = "16")
biome_counts_df <- rbind(biome_counts_df, new_row)
library(ggplot2)
library(dplyr)
library(scales)
## 
## Attaching package: 'scales'
## The following object is masked from 'package:viridis':
## 
##     viridis_pal
legend_labels <- c("1. Marine", "2. Coastal systems", "3. Inland wetlands", "4. Rivers and lakes","5. Tropical and subtropical forests", "6. Temperate forest and woodland", "7. Cold climate evergreen forest and woodland", "8. Shrubland and shrubby woodland","9. Rangelands and natural grasslands", "10. Desert and semi desert", "11. Polar and alpine systems", "12. Subterranean systems", 
                   "13. Intensive land use", "14. Anthropogenic systems", 
                   "15. Urban green and blue infrastructure", "16. Other")
ggplot(biome_counts_df, aes(x = Biome_Number, y = Frequency, color = Biome)) +
  geom_line(size = 1) +  # Thicker lines
  geom_point(size = 3) +  # White-filled points
  geom_path() +
  coord_polar(start = 0) +
  labs(title = "Biome Distribution",
       subtitle = "ESVD2.0_Biome",
       caption = "Source: ESVD MASTER 230616",
       x = NULL,  # Remove x-axis label
       y = NULL) +  # Remove y-axis label
  scale_y_continuous(labels = scales::comma) +
  scale_color_manual(values = custom_palette, labels = legend_labels) +  # Use custom color palette
  theme_light() +  # Minimal theme
  theme(legend.position = "right",  # Move legend to the bottom
        axis.text.x = element_text(angle = 45, hjust = 1, vjust = 1),  # Adjust x-axis text angle and position
        plot.title = element_text(size = 16, face = "bold"),  # Larger and bold title
        plot.subtitle = element_text(size = 12),  # Smaller subtitle
        legend.text = element_text(size = 10),  # Smaller legend text
        legend.key.size = unit(0.5, "cm"))  # Smaller legend key size
## Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
## ℹ Please use `linewidth` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
## `geom_line()`: Each group consists of only one observation.
## ℹ Do you need to adjust the group aesthetic?
## `geom_path()`: Each group consists of only one observation.
## ℹ Do you need to adjust the group aesthetic?

##1C ES
gathered_data2 <- gather(data, key = "Column", value = "ESs",
                        ES_1:ES_17)
gathered_data2 <- gathered_data2[c('ESs')]
head(gathered_data2)
##                                        ESs
## 1                                     Food
## 2                                     Food
## 3 Opportunities for recreation and tourism
## 4 Opportunities for recreation and tourism
## 5                                     Food
## 6 Opportunities for recreation and tourism
gathered_data2 <- subset(gathered_data2, !is.na(ESs) & ESs != "")

#Correct errors at the ES level
gathered_data2$ES <- NA
gathered_data2 <- gathered_data2 %>%
  separate_rows(ESs, sep = "; ")
gathered_data2 <- gathered_data2 %>%
  mutate(ESs = ifelse(ESs == "Existence, bequest value", "Existence, bequest values\n", ESs))
gathered_data2 <- gathered_data2 %>%
  mutate(ESs = ifelse(ESs == "Existence, bequest value", "Water purification ", ESs))

# Classify ES readings into categories
gathered_data2$ES[gathered_data2$ESs %in% c("Abatement of noise", "Waste treatment", "Water purification")] <- "11. Waste treatment"
gathered_data2$ES[gathered_data2$ESs %in% c("Aesthetic information", "Aesthetic information ", "Attractive landscapes")] <- "18. Aesthetic information"
gathered_data2$ES[gathered_data2$ESs == "Air quality regulation"] <- "7. Air quality regulation"
gathered_data2$ES[gathered_data2$ESs %in% c("Artistic inspiration", "Cultural use", "Inspiration for culture, art and design")] <- "20. Inspiration for culture, art and design"
gathered_data2$ES[gathered_data2$ESs %in% c("Bequest value", "Bequest values", "Existence", "Existence value", "Existence, bequest value", "Existence, bequest values", "Existence, bequest values", "Existence, bequest values")] <- "23. Existence, bequest values"
gathered_data2$ES[gathered_data2$ESs %in% c( "Biodiversity protection", "Maintenance of genetic diversity")] <- "17. Maintenance of genetic diversity"
gathered_data2$ES[gathered_data2$ESs == "Biological control"] <- "15. Biological control"
gathered_data2$ES[gathered_data2$ESs %in% c("Climate regulation", "Climate regulation ")] <- "8. Climate regulation"
gathered_data2$ES[gathered_data2$ESs %in% c("Ecotourism", "Opportunities for recreation ", "Opportunities for recreation and tourism", "Recreation", " Recreation", "Tourism")] <- "19. Opportunities for recreation and tourism"
gathered_data2$ES[gathered_data2$ESs %in% c("Erosion prevention", "Erosion prevention ")] <- "12. Erosion prevention"
gathered_data2$ES[gathered_data2$ESs %in% c("Fish", "Food")] <- "1. Food"
gathered_data2$ES[gathered_data2$ESs %in% c("Flood prevention", "Moderation of extreme events", "Prevention of extreme events [unspecified]")] <- "9. Moderation of extreme events"
gathered_data2$ES[gathered_data2$ESs == "Genetic resources"] <- "4. Genetic resources"
gathered_data2$ES[gathered_data2$ESs %in% c("Information for cognitive development")] <- "22. Information for cognitive development"
gathered_data2$ES[gathered_data2$ESs == "Maintenance of life cycles"] <- "16. Maintenance of life cycles"
gathered_data2$ES[gathered_data2$ESs %in% c("Maintenance of soil fertility", "Nutrient cycling")] <- "13. Maintenance of soil fertility"
gathered_data2$ES[gathered_data2$ESs == "Medicinal resources"] <- "5. Medicinal resources"
gathered_data2$ES[gathered_data2$ESs == "Ornamental resources"] <- "6. Ornamental resources"
gathered_data2$ES[gathered_data2$ESs %in% c("Other raw", "Raw materials", "Raw Materials", "Raw materials ")] <- "3. Raw materials"
gathered_data2$ES[gathered_data2$ESs == "Pollination"] <- "14. Pollination"
gathered_data2$ES[gathered_data2$ESs %in% c("Regulation of water flows", "Regulation of water flows  ", "Regulation of water flows")] <- "10. Regulation of water flows"
gathered_data2$ES[gathered_data2$ESs %in% c("Spiritual / Religious use", "Spiritual experience")] <- "21. Spiritual experience" 
gathered_data2$ES[gathered_data2$ESs == "Water"] <- "2. Water"

na_rows <- subset(gathered_data2, is.na(ES))
print(na_rows)
## # A tibble: 21 × 2
##    ESs                           ES   
##    <chr>                         <chr>
##  1 "Existence, bequest values\n" <NA> 
##  2 "Existence, bequest values\n" <NA> 
##  3 "Existence, bequest values\n" <NA> 
##  4 "Existence, bequest values\n" <NA> 
##  5 "Existence, bequest values\n" <NA> 
##  6 "Existence, bequest values\n" <NA> 
##  7 "Existence, bequest values\n" <NA> 
##  8 "Existence, bequest values\n" <NA> 
##  9 "Existence, bequest values\n" <NA> 
## 10 "Existence, bequest values\n" <NA> 
## # ℹ 11 more rows
ES_counts <- table(gathered_data2$ES)
ES_counts_df <- as.data.frame(ES_counts)
colnames(ES_counts_df) <- c("ES", "Frequency")
ES_counts_df$ES_general <- NA
ES_counts_df$ES_general[ES_counts_df$ES %in% c("1. Food", "2. Water", "3. Raw materials", "4. Genetic resources", "5. Medicinal resources", "6. Ornamental resources")] <- "Provisioning"
ES_counts_df$ES_general[ES_counts_df$ES %in% c("7. Air quality regulation", "8. Climate regulation", "9. Moderation of extreme events", "10. Regulation of water flows", "11. Waste treatment", "12. Erosion prevention", "13. Maintenance of soil fertility", "14. Pollination", "15. Biological control")] <- "Regulating"
ES_counts_df$ES_general[ES_counts_df$ES %in% c("16. Maintenance of life cycles", "17. Maintenance of genetic diversity")] <- "Habitat"
ES_counts_df$ES_general[ES_counts_df$ES %in% c("18. Aesthetic information", "19. Opportunities for recreation and tourism", "20. Inspiration for culture, art and design", "21. Spiritual experience", "22. Information for cognitive development", "23. Existence, bequest values")] <- "Cultural"

desired_order <- c("1. Food", "2. Water", "3. Raw materials", "4. Genetic resources", "5. Medicinal resources", "6. Ornamental resources",
                   "7. Air quality regulation", "8. Climate regulation", "9. Moderation of extreme events", "10. Regulation of water flows", "11. Waste treatment", "12. Erosion prevention", "13. Maintenance of soil fertility", "14. Pollination", "15. Biological control",
                   "16. Maintenance of life cycles", "17. Maintenance of genetic diversity",
                   "18. Aesthetic information", "19. Opportunities for recreation and tourism", "20. Inspiration for culture, art and design", "21. Spiritual experience", "22. Information for cognitive development", "23. Existence, bequest values")
ES_counts_df$ES <- factor(ES_counts_df$ES, levels = desired_order)

#ES Category
install.packages("ggrepel")
## Installing package into 'C:/Users/thali/AppData/Local/R/win-library/4.2'
## (as 'lib' is unspecified)
## package 'ggrepel' successfully unpacked and MD5 sums checked
## Warning: cannot remove prior installation of package 'ggrepel'
## Warning in file.copy(savedcopy, lib, recursive = TRUE): problema al copiar
## C:\Users\thali\AppData\Local\R\win-library\4.2\00LOCK\ggrepel\libs\x64\ggrepel.dll
## a C:\Users\thali\AppData\Local\R\win-library\4.2\ggrepel\libs\x64\ggrepel.dll:
## Permission denied
## Warning: restored 'ggrepel'
## 
## The downloaded binary packages are in
##  C:\Users\thali\AppData\Local\Temp\RtmpQf2ffK\downloaded_packages
library(ggrepel)
custom_palette <- viridis(23)

library(ggplot2)
ggplot(ES_counts_df, aes(x = "", y = Frequency, fill = ES)) +
  geom_bar(stat = "identity", width = 0.5) +
  coord_polar("y", start = 0) +
  scale_fill_manual(values = custom_palette) +
  geom_text(aes(label = paste0(round(Frequency / sum(Frequency) * 100), "%")), 
            position = position_stack(vjust = 0.5), size = 2.5, fontface = "bold", 
            colour = "white", check_overlap = TRUE) + 
  theme(legend.position = "right",
        legend.title = element_text(size = 20, face = "bold"),
        plot.title = element_text(size = 14, face = "bold"),
        plot.subtitle = element_text(size = 12), 
        plot.caption = element_text(size = 8)) +
  labs(title = "Distribution of Ecosystem Services",
       fill = "Ecosystem Service",
       subtitle = "ES_TEEB",
       caption = "Source: ESVD MASTER 230616") +
  theme_void() +
  theme(legend.position = "right") +
  geom_polygon(data = data.frame(x = c(0, rep(NA, 100), 0), 
                                 y = c(0, rep(NA, 100), 0)), 
               aes(x = x, y = y), fill = "white", color = NA)

VSL

##2 VSL
library(readxl)
library(tidyr)

#2A GEOGRAPHY
dataG <- read_excel("C:/Users/thali/OneDrive - Wageningen University & Research/Escritorio/MASTERS/13. 14. 15. Internship/TASKS/4. DUPLICATES AND HOTSPOTS/VSLxlsx.xlsx")
dataG <- separate_rows(dataG, Country, sep = ";")
country_counts <- table(dataG$Country)
country_counts_df <- as.data.frame(country_counts)
colnames(country_counts_df) <- c("Country", "Frequency")
country_counts_df$Country <- sub(",.*", "", country_counts_df$Country)
country_counts_df$Country <- gsub("^\\s+", "", country_counts_df$Country)
country_counts_df$Country <- trimws(country_counts_df$Country, "right")
print(country_counts_df)
##                                                Country Frequency
## 1                                              Algeria         1
## 2                                            Australia         1
## 3                                              Bolivia         2
## 4                                             Cambodia         1
## 5                                             Cameroon         1
## 6                                                China         1
## 7                                             Colombia         1
## 8                                           Costa Rica         2
## 9                                              Ecuador         1
## 10                                               Egypt         1
## 11                                         El Salvador         1
## 12                                             Finland         1
## 13                                              France         1
## 14                                       French Guiana         1
## 15                                           Guatemala         2
## 16                                              Guinea         1
## 17                                              Guyana         1
## 18                                            Honduras         1
## 19                                             Hungary         2
## 20                                             Ireland         1
## 21                                               Italy         1
## 22                                               Kenya         1
## 23                    Lao People's Democratic Republic         3
## 24                                                Mali         1
## 25                                              Mexico         1
## 26                                             Myanmar         1
## 27                                           Nicaragua         1
## 28                                               Niger         1
## 29                                             Nigeria         1
## 30                                              Norway         1
## 31                                            Pakistan         1
## 32                                              Panama         1
## 33                                                Peru         2
## 34                                              Poland         1
## 35                                            Portugal         1
## 36                                             Romania         2
## 37                                            Slovenia         1
## 38                                             Somalia         1
## 39                                           Sri Lanka         1
## 40                                               Sudan         1
## 41                                            Suriname         2
## 42                                              Sweden         1
## 43                                            Tanzania         2
## 44                                            Thailand         2
## 45                                              Turkey         1
## 46                                              Uganda         1
## 47  United Kingdom of Great Britain & Northern Ireland         2
## 48                            United States of America         3
## 49                                           Venezuela         1
## 50                                             Vietnam         2
## 51                                           Australia        18
## 52                                             Austria         6
## 53                                          Bangladesh         4
## 54                                             Belgium         4
## 55                                              Belize         4
## 56                                               Benin         1
## 57                                             Bermuda         1
## 58                                              Bhutan         1
## 59                                             Bolivia         1
## 60                                             Bonaire         3
## 61                                              Brazil        24
## 62                                            Bulgaria         1
## 63                                        Burkina Faso         4
## 64                                            Cambodia         3
## 65                                            Cameroon         2
## 66                                              Canada         7
## 67                                               China        50
## 68                                            Colombia         3
## 69                                          Costa Rica         6
## 70                                       Côte d'Ivoire         1
## 71                                                Cuba         2
## 72                                      Czech Republic         3
## 73                                             Denmark         5
## 74                                               Egypt         1
## 75                                         El Salvador         1
## 76                                            Ethiopia         5
## 77                                             Finland        15
## 78                                              France        14
## 79                                             Germany        65
## 80                                               Ghana         6
## 81                                              Greece         4
## 82                                           Guatemala         3
## 83                                              Guyana         1
## 84                                            Honduras         2
## 85                                           Hong Kong         3
## 86                                               India        27
## 87                                           Indonesia        23
## 88                                                Iran         6
## 89                                             Ireland         6
## 90                                              Israel         3
## 91                                               Italy        19
## 92                                               Japan         2
## 93                                              Jordan         1
## 94                                               Kenya         2
## 95                                               Korea         3
## 96                    Lao People's Democratic Republic         3
## 97                                             Lebanon         1
## 98                                             Liberia         1
## 99                                           Lithuania         1
## 100                                         Madagascar         2
## 101                                           Malaysia        18
## 102                                               Mali         5
## 103                                         Mauritania         2
## 104                                             Mexico        18
## 105                                            Moldova         1
## 106                                            Morocco         1
## 107                                         Mozambique         1
## 108                                            Myanmar         2
## 109                                              Nepal         3
## 110                                        Netherlands        34
## 111                                        New Zealand         3
## 112                                            Nigeria         6
## 113                                             Norway        10
## 114                                           Pakistan         3
## 115                                             Panama         4
## 116                                   Papua New Guinea         1
## 117                                               Peru         8
## 118                                        Philippines         6
## 119                                             Poland         9
## 120                                           Portugal        14
## 121                                            Romania         1
## 122                                 Russian Federation         2
## 123                                       Saudi Arabia         1
## 124                                            Senegal         5
## 125                                             Serbia         1
## 126                                    Solomon Islands         1
## 127                                       South Africa         6
## 128                                              Spain        45
## 129                                          Sri Lanka         5
## 130                                           Suriname         2
## 131                                             Sweden         8
## 132                                        Switzerland        10
## 133                                             Taiwan         3
## 134                                           Tanzania         1
## 135                                           Thailand         6
## 136                                             Turkey         9
## 137                                             Uganda         2
## 138                               United Arab Emirates         1
## 139 United Kingdom of Great Britain & Northern Ireland        27
## 140                           United States of America        85
## 141                                            Uruguay         2
## 142                                          Venezuela         1
## 143                                            Vietnam        10
## 144                                              World        14
## 145                                             Zambia         1
## 146                                           Zimbabwe         1
country_counts_df <- country_counts_df %>%
  filter(Country != "World")

country_lookup <- data.frame(
  non_standard_name = c("Lao People's Democratic Republic",
                        "United Kingdom of Great Britain & Northern Ireland",
                        "United States of America",
                        "Côte d'Ivoire",
                        "Russian Federation",
                        "Solomon Islands"),
  standard_name = c("Laos",
                    "United Kingdom",
                    "United States of America",
                    "Ivory Coast",
                    "Russia",
                    "Solomon Islands")
)

# Convert non-standard names to standard names
country_counts_df <- left_join(country_counts_df, country_lookup, by = c("Country" = "non_standard_name")) %>%
  mutate(Country = ifelse(is.na(standard_name), Country, standard_name))
country_counts_df <- country_counts_df[order(country_counts_df$Frequency, decreasing = TRUE), ]

# Load map data
world_map <- map_data("world")
library(rworldmap)
## Loading required package: sp
## The legacy packages maptools, rgdal, and rgeos, underpinning the sp package,
## which was just loaded, will retire in October 2023.
## Please refer to R-spatial evolution reports for details, especially
## https://r-spatial.org/r/2023/05/15/evolution4.html.
## It may be desirable to make the sf package available;
## package maintainers should consider adding sf to Suggests:.
## The sp package is now running under evolution status 2
##      (status 2 uses the sf package in place of rgdal)
## ### Welcome to rworldmap ###
## For a short introduction type :   vignette('rworldmap')
frequency.map <- joinCountryData2Map(country_counts_df, joinCode = "NAME", nameJoinColumn = "Country")
## 144 codes from your data successfully matched countries in the map
## 1 codes from your data failed to match with a country code in the map
## 139 codes from the map weren't represented in your data
library(ggplot2)
library(scales)
library(sf)
## Linking to GEOS 3.9.3, GDAL 3.5.2, PROJ 8.2.1; sf_use_s2() is TRUE
library(rnaturalearth)
library(rnaturalearthdata)
## 
## Attaching package: 'rnaturalearthdata'
## The following object is masked from 'package:rnaturalearth':
## 
##     countries110
world <- ne_countries(scale = "medium", returnclass = "sf")
frequency.world <- merge(world, country_counts_df, by.x="admin", by.y="Country")
world_map <- map_data("world")
ggplot(data = frequency.world) + 
  geom_map(data = world_map, map = world_map,
           aes(x = long, y = lat, map_id = region), fill = "lightgrey", color = "white") + # Add world map
  geom_sf(aes(fill=Frequency), color = "white") +  # Set border color to white
  scale_fill_gradient(name = "Density", limits = c(0, max(frequency.world$Frequency)), 
                      low = "lightblue", high = "darkblue") + # Customize the color scale
  labs(title = "Geographical Distribution of VSL Data; Density of Studies",
       caption = "Source: Valuation Studies List") + # Add a title
  theme_minimal() + # Use a minimal theme
  theme(plot.title = element_text(hjust = 0.5)) 
## Warning in geom_map(data = world_map, map = world_map, aes(x = long, y = lat, :
## Ignoring unknown aesthetics: x and y

#2B BIOME
library(dplyr)
dataB <- read_excel("C:/Users/thali/OneDrive - Wageningen University & Research/Escritorio/MASTERS/13. 14. 15. Internship/TASKS/4. DUPLICATES AND HOTSPOTS/Biomes.xlsx")
dataB <- separate_rows(dataB, Biome, sep = ";")
biomes_counts <- table(dataB$Biome)
biomes_counts_df <- as.data.frame(biomes_counts)
colnames(biomes_counts_df) <- c("Biome", "Frequency")
biomes_counts_df$Biome <- trimws(biomes_counts_df$Biome)
biomes_counts_df <- biomes_counts_df %>%
  group_by(Biome) %>%
  summarise(Frequency = sum(Frequency))
biomes_counts_df <- biomes_counts_df %>%
  mutate(Biome = case_when(
    Biome == "Open sea/ocean" ~ "1",
    Biome == "Coral reefs" ~ "1",
    Biome == "Coastal systems (incl wetlands)" ~ "2",
    Biome == "Inland wetlands" ~ "3",
    Biome == "Rivers and lakes" ~ "4",
    Biome == "Tropical forests" ~ "5",
    Biome == "Temperate forests" ~ "6",
    Biome == "Woodland & Shrubland" ~ "8",
    Biome == "Grass-/Rangeland" ~ "9",
    Biome == "Desert" ~ "10",
    Biome == "Tundra" ~ "8",
    Biome == "High mountain & Polar systems" ~ "11",
    Biome == "Inland Un- or Sparsely Vegetated" ~ "12",
    Biome == "Cultivated areas" ~ "13",
    Biome == "Rangelands and natural grasslands" ~ "9",
    Biome == "Desert and semi desert" ~ "10",
    Biome == "Polar and alpine systems" ~ "11",
    Biome == "Subterranean systems" ~ "12",
    Biome == "Intensive land use" ~ "13",
    Biome == "Urban Green and Blue Infrastructure" ~ "15",
    Biome == "Other" ~ "16",
    TRUE ~ Biome
  ))
new_row1 <- data.frame(Biome = "7", Frequency = 0)
new_row2 <- data.frame(Biome = "14", Frequency = 0)
biomes_counts_df <- rbind(biomes_counts_df, new_row1)
biomes_counts_df <- rbind(biomes_counts_df, new_row2)
biomes_counts_df <- biomes_counts_df %>%
  group_by(Biome) %>%
  summarize(Frequency = sum(Frequency))
biomes_counts_df <- biomes_counts_df %>%
  arrange(as.numeric(as.character(Biome)))
biomes_counts_df$Biome <- factor(biomes_counts_df$Biome)
print(levels(biomes_counts_df$Biome))
##  [1] "1"  "10" "11" "12" "13" "14" "15" "16" "2"  "3"  "4"  "5"  "6"  "7"  "8" 
## [16] "9"
library(forcats)
biomes_counts_df$Biome <- fct_inorder(biomes_counts_df$Biome)

library(ggplot2)
library(dplyr)
library(scales)
legend_labels <- c("1. Marine", "2. Coastal systems", "3. Inland wetlands", "4. Rivers and lakes",
                   "5. Tropical and subtropical forests", "6. Temperate forest and woodland", "7. Cold climate evergreen forest and woodland", "8. Shrubland and shrubby woodland",
                   "9. Rangelands and natural grasslands", "10. Desert and semi desert", "11. Polar and alpine systems", "12. Subterranean systems", 
                   "13. Intensive land use", "14. Anthropogenic systems", 
                   "15. Urban green and blue infrastructure", "16. Other")

# Radar plot with legend
custom_palette <- viridis(23)
ggplot(biomes_counts_df, aes(x = Biome, y = Frequency, color = Biome)) +
  geom_line(size = 1) +  # Thicker lines
  geom_point(size = 3) +  # White-filled points
  geom_path() +
  coord_polar(start = 0) +
  labs(title = "Frequency of Biomes",
       subtitle = "Unread Studies",
       caption = "Source: Valuation Studies List",
       x = NULL,  # Remove x-axis label
       y = NULL) +  # Remove y-axis label
  scale_y_continuous(labels = scales::comma) +
  scale_color_manual(values = custom_palette, labels = legend_labels) +  # Use custom color palette
  theme_light() +  # Minimal theme
  theme(legend.position = "right",  # Move legend to the bottom
        axis.text.x = element_text(angle = 45, hjust = 1, vjust = 1),  # Adjust x-axis text angle and position
        plot.title = element_text(size = 16, face = "bold"),  # Larger and bold title
        plot.subtitle = element_text(size = 12),  # Smaller subtitle
        legend.text = element_text(size = 10),  # Smaller legend text
        legend.key.size = unit(0.5, "cm"))  # Smaller legend key size
## `geom_line()`: Each group consists of only one observation.
## ℹ Do you need to adjust the group aesthetic?
## `geom_path()`: Each group consists of only one observation.
## ℹ Do you need to adjust the group aesthetic?

#2C ES
dataE <- read_excel("C:/Users/thali/OneDrive - Wageningen University & Research/Escritorio/MASTERS/13. 14. 15. Internship/TASKS/4. DUPLICATES AND HOTSPOTS/ES.xlsx")
dataE <- separate_rows(dataE, ES, sep = ";")
ES_counts <- table(dataE$ES)
ES_counts_df <- as.data.frame(ES_counts)
colnames(ES_counts_df) <- c("ES", "Frequency")
ES_counts_df$ES <- trimws(ES_counts_df$ES)
ES_counts_df <- ES_counts_df %>%
  group_by(ES) %>%
  summarise(Frequency = sum(Frequency))
ES_counts_df$ES[ES_counts_df$ES %in% c("Abatement of noise", "Waste treatment", "Water purification")] <- "11. Waste treatment"
ES_counts_df$ES[ES_counts_df$ES %in% c("Aesthetic information", "Aesthetic information ", "Attractive landscapes")] <- "18. Aesthetic information"
ES_counts_df$ES[ES_counts_df$ES == "Air quality regulation"] <- "7. Air quality regulation"
ES_counts_df$ES[ES_counts_df$ES %in% c("Artistic inspiration", "Cultural use", "Inspiration for culture, art and design")] <- "20. Inspiration for culture, art and design"
ES_counts_df$ES[ES_counts_df$ES %in% c("Bequest value", "Bequest values", "Existence", "Existence value", "Existence, bequest value", "Existence, bequest values", "Existence, bequest values", "Existence, bequest values")] <- "23. Existence, bequest values"
ES_counts_df$ES[ES_counts_df$ES %in% c( "Biodiversity protection", "Maintenance of genetic diversity")] <- "17. Maintenance of genetic diversity"
ES_counts_df$ES[ES_counts_df$ES == "Biological control"] <- "15. Biological control"
ES_counts_df$ES[ES_counts_df$ES %in% c("Climate regulation", "Climate regulation ")] <- "8. Climate regulation"
ES_counts_df$ES[ES_counts_df$ES %in% c("Ecotourism", "Opportunities for recreation ", "Opportunities for recreation and tourism", "Recreation", " Recreation", "Tourism")] <- "19. Opportunities for recreation and tourism"
ES_counts_df$ES[ES_counts_df$ES %in% c("Erosion prevention", "Erosion prevention ")] <- "12. Erosion prevention"
ES_counts_df$ES[ES_counts_df$ES %in% c("Fish", "Food")] <- "1. Food"
ES_counts_df$ES[ES_counts_df$ES %in% c("Flood prevention", "Moderation of extreme events", "Prevention of extreme events [unspecified]")] <- "9. Moderation of extreme events"
ES_counts_df$ES[ES_counts_df$ES == "Genetic resources"] <- "4. Genetic resources"
ES_counts_df$ES[ES_counts_df$ES %in% c("Information for cognitive development")] <- "22. Information for cognitive development"
ES_counts_df$ES[ES_counts_df$ES == "Maintenance of life cycles"] <- "16. Maintenance of life cycles"
ES_counts_df$ES[ES_counts_df$ES %in% c("Maintenance of soil fertility", "Nutrient cycling")] <- "13. Maintenance of soil fertility"
ES_counts_df$ES[ES_counts_df$ES == "Medicinal resources"] <- "5. Medicinal resources"
ES_counts_df$ES[ES_counts_df$ES == "Ornamental resources"] <- "6. Ornamental resources"
ES_counts_df$ES[ES_counts_df$ES %in% c("Other raw", "Raw materials", "Raw Materials", "Raw materials ")] <- "3. Raw materials"
ES_counts_df$ES[ES_counts_df$ES == "Pollination"] <- "14. Pollination"
ES_counts_df$ES[ES_counts_df$ES %in% c("Regulation of water flows", "Regulation of water flows  ", "Regulation of water flows")] <- "10. Regulation of water flows"
ES_counts_df$ES[ES_counts_df$ES %in% c("Spiritual / Religious use", "Spiritual experience")] <- "21. Spiritual experience" 
ES_counts_df$ES[ES_counts_df$ES == "Water"] <- "2. Water"
ES_counts_df <- ES_counts_df %>%
  arrange(ES)

ggplot(ES_counts_df, aes(x = "", y = Frequency, fill = ES)) +
  geom_bar(stat = "identity", width = 0.5) +
  coord_polar("y", start = 0) +
  scale_fill_manual(values = custom_palette) +
  geom_text(aes(label = paste0(round(Frequency / sum(Frequency) * 100), "%")), 
            position = position_stack(vjust = 0.5), size = 3, fontface = "bold", 
            colour = "white", check_overlap = TRUE) + 
  theme(legend.position = "right",
        legend.title = element_text(size = 20, face = "bold"),
        plot.title = element_text(size = 14, face = "bold"),
        plot.subtitle = element_text(size = 12), 
        plot.caption = element_text(size = 8)) +
  labs(title = "Distribution of Ecosystem Services",
       fill = "Ecosystem Service",
       subtitle = "Unread Studies",
       caption = "Source: Valuation Studies List") +
  theme_void() +
  theme(legend.position = "right") +
  geom_polygon(data = data.frame(x = c(0, rep(NA, 100), 0), 
                                 y = c(0, rep(NA, 100), 0)), 
               aes(x = x, y = y), fill = "white", color = NA)