##############################################################################################################
#
# SES : exemple de matrice pondérée par ensemble paysager. 
#
# Script : polar charts pour les services de la matrice pondérée
#   
# Auteur : Gbx AgroBioTech - Marie Pairon pour le compte du SPW
# Date : janvier 2023 (version 1.0)
#
##############################################################################################################

library(ggplot2)
library(png)

#get data
#--------------------------------------
#df_a<-read.csv('D:/DoX/NVE_Wallonie_II/REUNION/Formation_MatCap_janv2023/ENS_PAYS_MAT_POND.csv',sep=";")
df_a<-read.csv('D:/DoX/NVE_Wallonie_II/DATA/WP1_WORKING DOCS/Exemple_ARTIF/bouquets_resultats.csv',sep=";")

#calculate the orientation of the labels
#---------------------------------------
data_with_labels = df_a

# number of labels required
number_of_label <- nrow(data_with_labels)

# find the angle of rotation of the label
angle <-  90 - 360 * (data_with_labels$Index - 0.5) /number_of_label    

# check the label alignment - right or left
data_with_labels$hjust<-ifelse( angle < -90, 1, 0)
# check the label angle
data_with_labels$angle<-ifelse(angle < -90,
                               angle + 180, angle)


var<-names(df_a)

for (i in c(8:ncol(df_a)))
{
var_i<-var[i]

if(min(df_a[,var_i])<0) {ylimmin<-min(df_a[,var_i])} else {ylimmin<-0}

# Make the plot
#---------------------------------------------------
p_init <- ggplot(df_a, aes(x = as.factor(Index), # x-axis factor label
                      
                      # y-axis numerical parameter
                      y = df_a[,var_i],fill=Label)) +     
  
  # the bar height will represent
  # the actual value of the data
  geom_bar(stat = "identity")+
  scale_fill_manual(values = as.vector(df_a$Color))+
  
  
  # define size of inner circle
  # and the size of the bar
  
  ylim(ylimmin-1,max(df_a[,var_i])+1) +
  
  #min(df_a[,var_i])
  # define the polar coordinate
  coord_polar(start = 0)+
  
  # plot
  
  # add labels
  geom_text(data = data_with_labels,
            aes(x = Index, y =df_a[,var_i]+1,
                
                # label alignment
                label = Label, hjust=hjust),
            color = "black", fontface="bold",
            alpha = 0.6, size = 3,
            angle = data_with_labels$angle,
            inherit.aes = FALSE )+
  theme(
    plot.title = element_blank(),
    axis.title.x = element_blank(),
    axis.title.y = element_blank(),
    legend.position = "none",
    axis.ticks.x = element_blank(),
    axis.text.x = element_blank(),
    axis.ticks.y = element_blank(),
    axis.text.y = element_blank(),
    plot.background = element_rect(fill = "white"),
    panel.background = element_rect(fill = "white"),
    axis.line.x = element_line(color = "white")
  )

p_init

ggsave(paste0("D:/DoX/NVE_Wallonie_II/REUNION/Formation_MatCap_janv2023/Bouquet_",var_i,".png"),plot=p_init,width=6 ,height= 4)

}

