# Load necessary libraries
library(FactoMineR)
library(factoextra)
library(ggrepel)

# Assigning data frame
df <- as.data.frame(AUGMENTED_DESIGN_DATA_FOR_ANALYSIS)  # Convert tibble to data frame

# Set the row names to the identifiers from the first column
row.names(df) <- df[, 1]


# Scale the data excluding the first column (genotype names)
data.scaled <- scale(x = data[, -1], center = TRUE, scale = TRUE)

# Perform PCA
PC <- PCA(data.scaled, graph = FALSE)

# Extract PCA coordinates for individuals (rows)
PC_coords <- data.frame(PC$ind$coord)
colnames(PC_coords) <- c("PC1", "PC2")

# Extract genotype labels from the first column of the original data
labels <- as.character(data[, 1])

# Combine PC coordinates and labels into one data frame
plot_data <- data.frame(PC_coords, labels)

# Create the biplot with points only (no individual labels)
p <- fviz_pca_biplot(PC, repel = TRUE,
                     pointsize = 1.5,
                     geom.var = c("arrow", "text"),  # Show variable arrows and labels
                     geom.ind = "point",            # Show individual points (no labels)
                     axes = c(1, 2),                # Use PC1 and PC2
                     col.var = "black") +           # Variable color
  geom_text_repel(data = plot_data,                 # Add genotype labels
                  aes(x = PC1, y = PC2, label = labels),
                  size = 3, color = "forestgreen", max.overlaps = 60,
                  segment.color = NA) +             # Remove connecting lines
  labs(title = "Biplot (axes PC1 and PC2: 39.3%)",
       x = "PC1 (26.5%)",
       y = "PC2 (12.8%)") +
  theme(text = element_text(size = 10, colour = "black"),
        legend.text = element_text(size = 10),
        axis.title.y = element_text(size = 10),
        axis.line = element_line(linewidth = 0.3, colour = "black"),
        panel.background = element_rect(fill = "white"),
        plot.background = element_rect(fill = "white", color = "black", linewidth = 0.3),
        axis.text.y = element_text(colour = "black", size = 10),
        axis.text.x = element_text(angle = 0, hjust = 0.5, vjust = 0.3, size = 10, colour = "black"),
        plot.title = element_text(hjust = 0.5))     # Center the title

# Print the plot
print(p)

# Save the plot
ggsave("Fig9.png", plot = p, device = "png", dpi = "print", height = 4.5, width = 5.5)
ggsave("Fig9.eps", plot = p, device = "eps", dpi = "print", height = 4.5, width = 5.5)