
# Set working directory 

# Anyone using this script will need to adjust this line to their local path.
working_directory = setwd("D:/SLR/Bonn_data_slr")

library(readxl) # read excel file
library(writexl) # export excel file
library(dplyr)
library(ggplot2)
library(tidyverse)
library(ggplot2) #  ggplot2.org , website 


# visualization library 
library(RColorBrewer) # to select colors for graph & maps 
library(ggthemes) # to select the graph background design for example, theme_stata,theme_tufte, 
library(extrafont) # to change the font in the graph 
display.brewer.all() # to show the color sets


# Read original data frame ####

df <- read_excel("9.Dataset2_all_records_without_two_papers.xlsx")

# explore the data in R
dim(df) # shows the dimensions of the data frame by row and column
str(df) #shows the structure of the data frame
summary(df) #shows the descriptive statistics of each column in the data frame
names(df)  #shows the name of each column in the data frame
colnames(df)  #shows the name of each column in the data frame
head(df) #shows the first 6 rows of the data frame
tail(df) # shows the last 6 rows of the data frame
View(df) #shows a spreadsheet-like display of the entire data frame in new window
class(df)
glimpse(df)

# Read metadata ####
metadata <- read_excel("7.Metadata_SLR_23012024.xlsx")


names(metadata)
view(metadata)
glimpse(metadata)
print(ncol(df))
print(length(metadata$Variable_name))
# Rename the head columns of the data as mapped in the metadata
colnames(df) <- metadata$Variable_name
glimpse(df)

# 1. Create timeline graph ####
##sub-setting the data frame for timeline publication using the metadata 

mask<- metadata$Timeline 
timeline<- df[mask] 
head(timeline)
View(timeline)
is.data.frame(timeline)


## Create the stacked area chart
library(tidyverse)
library(patchwork)
library(cowplot)
# Ensure Participatory is a factor with correct levels
timeline$Participatory <- factor(timeline$Participatory, levels = c("0", "1"),
                             labels = c("Non_participatory", "Participatory"))
# lablel with normal dash not underscore 
custom_labels <- c("Non_participatory" = "Non-participatory", "Participatory" = "Participatory")

# group the data 
timeline2 <- timeline %>%
  group_by(Year, Participatory) %>%
  summarise(count = n(), .groups = 'drop')


### define the colors 
colors1 <- c("Non_participatory" = "#FF7F50" ,  "Participatory" = "#008080" )  
colors2 <- c( "Participatory" = "#FF5733" , "Non_participatory"  = "#87CEEB" )  


# Create the stacked area chart
timeline3 <- ggplot(timeline2, aes(x = Year, y = count, fill = Participatory)) + 
  geom_area(position = "stack") +
  scale_fill_manual(values = colors2, name = "Valuation approach", labels = custom_labels )+ 
  scale_x_continuous(breaks = seq(min(timeline2$Year), max(timeline2$Year), by = 1)) +
  labs(x = "Year of publication", y = "Number of papers") + 
  theme_minimal() +
  theme(axis.title = element_text(size = 15),
        axis.text.x = element_text(angle = 45, hjust = 1, size = 10, colour ='black'),
        axis.text.y = element_text(size = 10, colour = 'black'), 
        legend.title = element_text(size = 15),
        legend.text = element_text(size = 12)) 


# Pie chart data preparation
pie_data <- timeline %>%
  count(Participatory) %>%
  mutate(percentage = n / sum(n) * 100)

# Pie chart
pie_plot <- ggplot(pie_data, aes(x = "", y = n, fill = Participatory)) +
  geom_bar(width = 1, stat = "identity") +
  coord_polar(theta = "y") +
  scale_fill_manual(values = colors2) +
  geom_text(aes(label = paste(n, "\n(", round(percentage, 1), "%)", sep = "")), position = position_stack(vjust = 0.5)) +
  theme_void()+
guides(fill = "none")
## Combine the two plots 
combined_plot <- ggdraw() +
  draw_plot(timeline3) +
  draw_plot(pie_plot, x = 0.05, y = 0.40, width = 0.50, height = 0.50)
# Adjust margins of the pie chart
combined_plot <- combined_plot + theme(plot.margin = unit(c(1, 0.25, 1, 1.2), "cm"))

# Display the combined plot
print(combined_plot)

## Save the plot 
# to specific directory
file_timeline <- "D:/SLR/Analysis/Results/timeline.tiff"
ggsave(filename = file_timeline , plot = combined_plot, width = 25, height = 15, units = "cm", dpi = 300, bg = "white")

# Save the combined plot 
# to working directory 
ggsave("timeline2.tiff", combined_plot, width = 25, height = 15, units = "cm", dpi = 300, bg = "white")
#### End of timeline graph 


# 2. Create venn graph ####
# library 
library("ggvenn")
library("VennDiagram")

##sub-setting the data frame for es using the metadata
mask<- metadata$ES_venn 
es <- df[mask] 
head(es)
View(es)
# selecting data from the es data frame
parti_es <- filter(es, Participatory == "1")
non_parti_es <- filter(es, Participatory == "0")
subset(non_parti_es, select = -(2)) ## remove ecosystem function column
view(non_parti_es)
# transforming data to logical values for participatory 
parti_es$Regulating <- as.logical(parti_es$Regulating_services)
parti_es$Provisioning <- as.logical(parti_es$Provisioning_services)
parti_es$Cultural<- as.logical(parti_es$Cultural_services)

## 2.1 Creating venn digram for services in participatory research ####
venn_plot_parti<- ggvenn(parti_es, c("Regulating", "Provisioning", "Cultural"))
print(venn_plot_parti)
## save it to specific directory 
venn_parti <- "D:/SLR/Analysis/Results/venn_parti.tiff"
ggsave(filename = venn_parti , plot = venn_plot_parti , width = 13, height = 15, units = "cm", dpi = 300, bg = "white")

## or save it to working directory 
ggsave("venn_parti.tiff", venn_plot, width = 8, height = 8)
# end of participatory venn diagram ##

#transforming data to logical values for non participatory 

non_parti_es $Regulating<- as.logical(non_parti_es$Regulating_services)
non_parti_es $Provisioning<- as.logical(non_parti_es$Provisioning_services)
non_parti_es $Cultural<- as.logical(non_parti_es$Cultural_services)

## 2.2 Creating venn digram for services in non-participatory research ####
venn_plot_nonparti<- ggvenn(non_parti_es, c("Regulating", "Provisioning", "Cultural"))

## save it to specific directory 
venn_nonparti <- "D:/SLR/Analysis/Results/venn_nonparti.tiff"
ggsave(filename = venn_nonparti , plot = venn_plot_nonparti, width = 13, height = 15, units = "cm", dpi = 300, bg = "white")

## or save it to work directory 
ggsave("venn_nonparti.tiff", venn_plot, width = 8, height = 8)

#### end of the venn diagram 




## 2.3 Try to do upset graph to ecosystem services #### 



library(ComplexUpset)
library(UpSetR)
library(devtools)


### source from this video https://youtu.be/6nN9RC6Exus?t=610
### https://cran.r-project.org/web/packages/ComplexUpset/vignettes/Examples_R.html
### https://krassowski.github.io/complex-upset/articles/Examples_R.html#fill-the-bars
### https://github.com/hms-dbmi/UpSetR/issues/59
### https://stackoverflow.com/questions/54770795/stacked-barplot-in-upsetr/56704255#56704255

### 2.3.1 Upset for participatory papers ####

# Define your color variables
main_bar_col <-  "#FF5733" # Color for the main bars, "#800080"
sets_bar_col <- "#FF5733"  # Color for the set size bars
matrix_col <- "#000000"  # Color for the matrix, "#000000" 
shade_col <- "#D3D3D3"     # Light gray color for the shade

# Define your text scale options
text_scale_options3 <- c(1.5, 1.5, 1.5, 1.5, 1.5)  # Example scaling factors for various text elements

# Define your main bar to set size bar ratio
mb_ratio <- c(0.7, 0.3)  # Example ratio; adjust as needed

## upset for participatory es 
set_var <- c ( "Regulating_services", "Provisioning_services", "Cultural_services", "Ecosystem_function")

upset_parti<- upset(parti_es,
                    sets= set_var,
                    mb.ratio = mb_ratio,
                    mainbar.y.label = "Number of papers",
                    sets.x.label = "Number of papers", 
                    order_by( "freq"),
                    show.numbers = TRUE, 
                    point.size= 1.5, 
                    line.size = 1, 
                    text.scale = text_scale_options3,
                    main.bar.color = main_bar_col,
                    sets.bar.color= sets_bar_col,
                    matrix.color = matrix_col,
                    shade.color = shade_col
)



#saving the plot to a file, start the TIFF device again
tiff("upset_plot_with_title.tiff", width = 2400, height = 2400, res = 300)
print(upset_parti)
dev.off()




### 2.3.2 Upset for nonparticipatory es ####
non_parti_es2 <- filter(es, Participatory == "0")
# Define your color variables
main_bar_col <-  "#87CEEB" # Color for the main bars, "#800080"
sets_bar_col <- "#87CEEB"  # Color for the set size bars
matrix_col <- "#000000"  # Color for the matrix, "#000000" 
shade_col <- "#D3D3D3"     # Light gray color for the shade

# Define your text scale options
text_scale_options3 <- c(1.5, 1.5, 1.5, 1.5, 1.5)  # Example scaling factors for various text elements

# Define your main bar to set size bar ratio
mb_ratio <- c(0.7, 0.3)  # Example ratio; adjust as needed

set_var2 <- c ( "Regulating_services", "Provisioning_services", "Cultural_services")

upset_nonparti<- upset(non_parti_es2,
                    sets= set_var2,
                    mb.ratio = mb_ratio,
                    mainbar.y.label = "Number of papers",
                    sets.x.label = "Number of papers", 
                    order_by( "freq"),
                    show.numbers = TRUE, 
                    point.size= 1.5, 
                    line.size = 1, 
                    text.scale = text_scale_options3,
                    main.bar.color = main_bar_col,
                    sets.bar.color= sets_bar_col,
                    matrix.color = matrix_col,
                    shade.color = shade_col
)

#saving the plot to a file, start the TIFF device again
tiff("upset_plot_nonparti.tiff", width = 2400, height = 2400, res = 300)
print(upset_nonparti)
dev.off()
# end of the upset graph ##


# 3. Create valuation unit graph ####

##sub-setting the data frame for es using the metadata 
mask<- metadata$Valuation_units 
valuation_units <- df[mask] 
View(valuation_units)
head(valuation_units)
names(valuation_units) <- gsub("_services$", "", names(valuation_units)) # remove the word services 

# First, mutation to create BN_SN, BN_SE, BN_H, etc.
valuation_units2 <- valuation_units %>%
  mutate(
    BN_SN = as.numeric(BN == 1 & SN == 1),
    BN_SE = as.numeric(BN == 1 & SE == 1),
    BN_H = as.numeric(BN == 1 & Health == 1),
    BE_SN = as.numeric(BE == 1 & SN == 1),
    BE_SE = as.numeric(BE == 1 & SE == 1),
    BE_H = as.numeric(BE == 1 & Health == 1),
    SN_H = as.numeric(SN == 1 & Health == 1),
    SE_H = as.numeric(SE == 1 & Health == 1)
  )

# Second, mutation to create the Services column (Continue from valuation_units2, not redo from valuation_units)
valuation_units2 <- valuation_units2 %>%
  mutate(
    Services = case_when(
      Regulating == 1 & Provisioning == 0 & Cultural == 0 ~ "Regulating",
      Regulating == 0 & Provisioning == 1 & Cultural == 0 ~ "Provisioning",
      Regulating == 0 & Provisioning == 0 & Cultural == 1 ~ "Cultural",
      Regulating == 1 & Provisioning == 1 & Cultural == 0 ~ "Regulating & Provisioning",
      Regulating == 1 & Provisioning == 0 & Cultural == 1 ~ "Regulating & Cultural",
      Regulating == 0 & Provisioning == 1 & Cultural == 1 ~ "Provisioning & Cultural",
      Regulating == 1 & Provisioning == 1 & Cultural == 1 ~ "All Services",
      TRUE ~ "No Service"
    )
  )

# Third, mutation to adjust based on combinations (Continue from the last updated version of valuation_units2)
df_adjusted <- valuation_units2 %>%
  mutate(
    BN_adj = ifelse(BN_SN + BN_SE + BN_H > 0, 0, BN),
    BE_adj = ifelse(BE_SN + BE_SE + BE_H > 0, 0, BE),
    SN_adj = ifelse(SN_H > 0, 0, SN),
    SE_adj = ifelse(SE_H > 0, 0, SE),
    Health_adj = ifelse(BN_H + BE_H + SN_H + SE_H > 0, 0, Health)
  )




# fourth ,Reshaping and summarizing the adjusted data, assuming code is a unique identifier for each paper.
df_long <- df_adjusted %>%
  pivot_longer(
    cols = c(BN_adj, BE_adj, SN_adj, SE_adj, Health_adj, BN_SN, BN_SE, BN_H, BE_SN, BE_SE, BE_H, SN_H, SE_H),
    names_to = "valuation_unit",
    values_to = "presence" # Changed to 'presence' to reflect this is a binary indicator
  ) %>%
  filter(presence > 0) %>%
  distinct(Code, .keep_all = TRUE) %>% # Assuming you have a unique identifier column 'paper_id'
  group_by(Participatory, Services, valuation_unit) %>%
  summarize(paper_count = n_distinct(Code), .groups = 'drop') # Count distinct papers
sum(df_long$paper_count)



# Fifth, renaming the valuation unit columns by removing the "_adj" suffix

library(stringr)

df_long <- df_long %>%
  mutate(valuation_unit = str_replace(valuation_unit, "_adj", ""))

# Checking the renamed columns
head(df_long)
sum(df_long$paper_count)

df_long <- df_long %>%
  mutate(valuation_unit = str_replace_all(valuation_unit, "_", " "))

library(forcats)  # for fct_recode

str(df_long$Participatory)

# Update the Participatory column to be a factor with readable levels
df_long$Participatory <- factor(df_long$Participatory, levels = c("0", "1"))
is.factor(df_long$Participatory)

df_long$Participatory <- fct_recode(df_long$Participatory,
                                    "Non-Participatory" = "0",
                                    "Participatory" = "1")


## optional step ####

## if I want to know the total number of each bar 
### Calculate total counts for each valuation unit within each Participatory group 
df_totals <- df_long %>% # df totals and df_long joined with total are not necessary for graph plot only to know the exact number of papers for each bar
  group_by(Participatory, valuation_unit) %>%
  summarize(paper_count = sum(paper_count), .groups = 'drop')

### Merge the total counts back into the long data frame for plotting ,careful with this step as not needed for the graph
df_long <- df_long %>%
  left_join(df_totals, by = c("Participatory", "valuation_unit"))

# continue in the code for the valuation unit #####
# Sixth, NICE  stacked bar chart with readable facet labels and a nice color palette 
valuation_units_plot<- ggplot(df_long, aes(x = valuation_unit, y = paper_count, fill = Services)) +
  geom_bar(stat = "identity", position = "stack") +
  facet_grid(~ Participatory, scales = "free_x", space = "free_x") +
  scale_fill_brewer(palette = "Paired") + 
  theme_minimal() +
  labs(
    title = "", ##I can add the title here 
    x = "Valuation Units",
    y = "Number of Papers",
    fill = "Ecosystem Services"
  ) +
  scale_y_continuous (
    breaks = seq(0, 40, by = 10), 
    limits = c(NA,40)) +             
  theme(
    axis.text.x = element_text(color = "black"), # Set x-axis label color to black
    panel.grid.major = element_line(size = 0.5, color = "grey80"), ###
    panel.grid.minor = element_blank(), ###
    strip.text.x = element_text(size = 12, face = "bold"), # Bold facet labels
    legend.position = "bottom", # Legend at the bottom
    panel.spacing = unit(1, "lines"), # Space between the facets
    panel.border = element_rect(colour = "black", fill = NA, size = 0.5), # Borders to separate facets
    axis.ticks.length = unit(0, "points"), # No axis ticks to clean up the look
    panel.background = element_rect(fill = "white", colour = NA) 
    )

print(valuation_units_plot)

## now saving the graph ##
setwd("D:/SLR/Analysis/Results")
ggsave(filename = "valuation_units.tiff", plot = valuation_units_plot, device = "tiff", path = "D:/SLR/Analysis/Results", width = 19, height = 9, units = c("cm"), dpi = 700, bg = "white")

## save it as jpg image 
ggsave("valuation units.jpg", width = 19, height = 9, units = c("cm"),dpi = 700,bg = "white")


##### end of the code for the nice graph , simple and clear 


# 4. Drivers of change graph ####

## sub-setting the data frame for drivers using the metadata

mask<- metadata$Drivers_change
drivers <- df[mask] 
head(drivers)
View(drivers)
is.data.frame(drivers)


# First, count the data for the graph
drivers2 <- drivers %>%
  group_by(Drivers_of_change, Participatory) %>%
  count() %>%
# Calculate the total count for each drivers of change category
  group_by(Drivers_of_change) %>%
  mutate(Total = sum(n)) %>%
# Calculate percentage within each Participatory group
  mutate(Percentage = (n / Total) * 100) 


# Ensure 'Drivers_of_change' and 'Participatory' are factors, and rename it 
drivers2$Participatory <- factor(drivers2$Participatory, levels = c(0, 1), labels = c("Non-participatory", "Participatory"))

drivers2$Drivers_of_change <- factor(drivers2$Drivers_of_change,  levels = c(0, 1), labels = c("Without drivers of change", "With drivers of change"))



# Reorder and rename the levels of the 'Drivers_of_change' factor variable

drivers2$Participatory<- factor(drivers2$Participatory, levels = c("Participatory", "Non-participatory"), labels = c("Participatory", "Non-participatory"))

drivers2$Drivers_of_change <- factor(drivers2$Drivers_of_change, levels = c("With drivers of change", "Without drivers of change"), labels = c("With drivers of change", "Without drivers of change"))

## coloring 
colors2 <- c( "Participatory" = "#FF5733" , "Non-participatory"  = "#87CEEB" )  


# Plotting the data
driversplot <- ggplot(drivers2, aes(x = Drivers_of_change, y = n, fill = Participatory)) + 
  geom_bar(stat = "identity", position = "stack") + # Use stacked bars
  geom_text(aes(label = n), vjust = -0.5, size = 4, position = position_stack(vjust = 0.5)) + # Show count of papers
  geom_text(aes(label = paste0("(", round(Percentage, 1), "%)"), y = n), vjust = 1.5, size = 4, position = position_stack(vjust = 0.5)) + # Show percentage with parentheses
  scale_y_continuous(breaks = seq(0, 90, by = 10), limits = c(0, 90)) + 
  scale_fill_manual(values = colors2, name = "Valuation approach") +
  labs(x = "Drivers of change", y = "Number of papers")+
    theme(axis.title=element_text(size=15),
     axis.text=element_text(size=10, colour = 'black'),
     legend.position = "right",  
     legend.text=element_text(size=14),
     legend.title = element_text(size = 18),
     legend.key.size = unit(0.50, 'cm'))
      
          
  
driversplot

file_path <- "D:/SLR/Analysis/Results/drivers_of_change4.tiff"

# Save the plot
ggsave(filename = file_path, plot = driversplot, width = 8, height = 6, dpi = 300)


#### colors options####
colors3 <- c("Without drivers of change" = "#fdae61",  # A warm, soft orange
             "With drivers of change" = "#008080")  # A cool, soothing blue

colors4 <- c("Without drivers of change" = "#26A69A",  # Vibrant teal
             "With drivers of change" = "#6A1B9A")    # Deep purple

colors5 <- c("With drivers of change" = "#80CBC4",  # Gentle pastel teal
             "Without drivers of change" = "#B39DDB")

colors6 <- c("Without drivers of change" = "#BCAAA4",  # Muted brown
             "With drivers of change" = "#A5D6A7")    # Soft pastel green

colors7 <- c("Without drivers of change" = "#E6C17B",  # Muted, earthy orange
             "With drivers of change" = "#A5D6A7")    # Pastel green

####end of of valuation approach and drivers of change plot ##

















# 5.  Create analysis methods ####
#source: 
## https://cran.r-project.org/web/packages/eulerr/vignettes/gallery.html
## http://127.0.0.1:27935/graphics/plot_zoom_png?width=1024&height=520

library(eulerr)
library(grid)
library(gridExtra)
# subset the data from the df 
mask<- metadata$Analysis_methods
methods <- df[mask]
head(methods)

# Filter for participatory papers
df_participatory <- methods[methods$Participatory == 1, ]

# Fit Euler diagrams

fit_participatory <- euler(df_participatory[, c( "Statistical_modelling_equations", 
                                                 "Spatial_Remote_sensing", "Conceptual_framework", "Content_thematic_analysis", "Theory")])


# Custom labels for the diagram
custom_labels <- c("Statistical Modelling and equations", "Spatial - remote sensing", 
                   "Conceptual and methodological framework", "Content and thematic analysis", "Theoretical analysis")

# Set margins for additional space 
par(mar = c(6, 4, 4, 2))  # Adjust the top margin (third value) to make space for the title

# Add a legend manually since eulerr's plot function doesn't have a built-in legend argument
legend("topright",  # Adjust the position as needed
       legend = custom_labels,
       col = c("lavenderblush2", "lightblue2", "lightsalmon", "plum2", "palegreen2"),
       lty = 1, cex = 2,
       pch = 19)

# Create and save the plot for participatory


plot_participatory <- plot(fit_participatory, 
                            labels = list(fontfamily = "serif", 
                                          labels = c("Statistical modelling and equations", 
                               "Spatial - remote sensing", 
                  "Conceptual and methodological framework", 
                    "Content and thematic analysis", 
                    "Theoretical analysis"),
                  cex = 1.2  ),
                  quantities = list(type = c("counts", "percent"),
                  font=3, round=2, cex= 0.95),
                  edges = list(lty = 3), 
                  fills = c("lavenderblush2", "lightblue2", "lightsalmon", "plum2", "palegreen2"))


# remove the title 
mtext("Participatory papers", side = 1, line = 5, col = "blue", font = 4, cex = 2)


print(plot_participatory)


file_path <- "D:/SLR/Analysis/Results/parti_methods3.tiff"

# Save the plot
ggsave(filename = file_path, plot = plot_participatory, width = 8, height = 6, dpi = 300)

# removed line
#Customize the title appearance if needed
title(main = "Participatory papers", col.main = "blue", font.main = 5, cex.main = 2, mgp = c(3, 2, 0))


## non participatory 
# Filter data for non-participatory
df_non_participatory <- methods[methods$Participatory == 0, ]

# Fit Euler diagram for non-participatory
fit_non_participatory <- euler(df_non_participatory[, c( "Statistical_Modelling_equations", 
                                                  "Spatial_Remote_sensing", "Conceptual_framework", "Content_thematic_analysis", "Theory")])

plot_nonparticipatory <- plot(fit_non_participatory,
                              labels = list(fontfamily = "serif", 
                                            labels = c("Statistical modelling and equations", 
                                                       "Spatial - remote sensing", 
                                                       "Coceptual and methodological framework", 
                                                       "Content and thematic analysis", 
                                                       "Theoretical analysis"),
                                            cex = 1.2  ),
                              quantities = list(type = c("counts", "percent"), font=3, round=2, cex= 0.95),
                              edges = list(lty = 3), 
                              fills = c("lavenderblush2", "lightblue2", "lightsalmon", "plum2", "palegreen2"))



# remove the title 
mtext("Non-participatory papers", side = 1, line = 5, col = "blue", font = 4, cex = 2)


print(plot_nonparticipatory)

file_path <- "D:/SLR/Analysis/Results/nonparti_methods3.tiff"

# Save the plot
ggsave(filename = file_path, plot = plot_nonparticipatory, width = 8, height = 6, dpi = 300)



# removed line
# Customize the title appearance if needed
title(main = "Non-participatory papers", col.main = "blue", font.main = 4, cex.main = 2 , mgp = c(3, 2, 0))
#### end of analysis methods graph### 






# 6. Create table of descriptive statistics ####


mask<- metadata$General_table
general <- df[mask] 
head(general)
View(general)
is.data.frame(General)

df_participatory <- general[general$Participatory == 1, ]
df_non_participatory <- general[general$Participatory == 0,]

str(df_non_participatory)
## count per variable 
table(df_non_participatory$Scenario)
table(df_non_participatory$Ecosystem_services_tradeoff)
table(df_non_participatory$Forest_ecosystem_alone)
table(df_non_participatory$One_forest_type)



#7 Economic valuation ####
mask<- metadata$Economic_valuation
economic <- df[mask] 
head(economic )
View(economic )
is.data.frame(economic )
str(economic)


economic2 <- economic %>%
  group_by(Economic_valuation, Participatory) %>%
  count() %>%
  # Calculate the total count for each Participatory category
  group_by(Economic_valuation) %>%
  mutate(Total = sum(n)) %>%
  # Calculate percentage within each Participatory group
  mutate(Percentage = (n / Total) * 100) 


# Ensure 'Economic_valuation' and 'Participatory' are factors, and rename it 
economic2$Participatory <- factor(economic2$Participatory, levels = c(0, 1), labels = c("Non-participatory", "Participatory"))
economic2$Economic_valuation <- factor(economic2$Economic_valuation,  levels = c(0, 1), labels = c("Without economic valuation", "With economic valuation"))

## coloring 
colors2 <- c( "Participatory" = "#FF5733" , "Non-participatory"  = "#87CEEB" ) 

# Plotting the data
economicplot <- ggplot(economic2, aes(x = Economic_valuation , y = n, fill = Participatory )) + 
  geom_bar(stat = "identity", position = "stack") + # Use stacked bars
  geom_text(aes(label = n), vjust = -0.5, size = 4, position = position_stack(vjust = 0.5)) + # Show count of papers
  geom_text(aes(label = paste0("(", round(Percentage, 1), "%)"), y = n), vjust = 1.5, size = 4, position = position_stack(vjust = 0.5)) + # Show percentage with parentheses
  scale_y_continuous(breaks = seq(0, 90, by = 15), limits = c(0, 90)) + 
  scale_fill_manual(values = colors2, name = "Valuation approach") +
  labs(x = "Economic valuation", y = "Number of papers")+
  theme(axis.title=element_text(size=15),
        axis.text=element_text(size=10, colour = 'black'),
        legend.position = "right",  
        legend.text=element_text(size=14),
        legend.title = element_text(size = 18),
        legend.key.size = unit(0.50, 'cm'))


economicplot

file_path <- "D:/SLR/Analysis/Results/economic_valuation2.tiff"

# Save the plot
ggsave(filename = file_path, plot =economicplot, width = 8, height = 6, dpi = 300)

####end of of valuation approach and drivers of change plot ##


# 8. Citation for r and packages ####
# explanation 
# run the citation function , then cop the Bibtex entry in text file inside r # then save the text #file .Bib , after saving the file import it to reference # manager ar bibtex file and all reference #will be automatically added BINGOO :) 
#source:  https://youtu.be/zuuOYjE8m98


citation() ## cite r
version$version.string  ## cite the version
citation("ggplot2")
citation("dplyr")
citation("tidyverse")

# visualization library 
citation("RColorBrewer")  
citation("ggthemes") 
citation("extrafont")
## timeline 
citation ("patchwork")
citation ("cowplot")
## venn 

citation ("ggvenn")
citation ("VennDiagram")
## upset 
citation ("ComplexUpset")
citation ("UpSetR")
citation ("devtools")

## eulerr

citation ("eulerr")
citation ("grid")
citation ("gridExtra")
