I'm trying to create a biplot in ggplot2 and manage to do it after a lot of trail and errors, But I can't get rid of the a
from the legend. I think the difficulty arrise from the fact, that the data set is not set globally, but inside the geom_segment()
command. But I can't find a way around it. The code is below as well as the output.
In the legend I get the a
with the colours. I would like to know how I can get rid of the a
and how I can set specific colours to this groups.
thanks in advance
library(ggplot2)
data <- matrix(rnorm(100), nrow = 10, ncol = 6)
colnames(data) <- c("gene1", "gene2", "gene3", "gene4", "gene5", "gene6")
pca_result <- prcomp(data, center = TRUE, scale. = TRUE)
scores <- as.data.frame(pca_result$x)
scores$sample <- rownames(scores)
loadings <- as.data.frame(pca_result$rotation)
loadings$variable <- rownames(loadings)
loadings$group <- rep(c("group1", "group2", "group3"), each = 2)
explained_variance <- summary(pca_result)$importance[2, ]
percent_var_PC1 <- round(explained_variance[1] * 100, 1)
percent_var_PC2 <- round(explained_variance[2] * 100, 1)
ggplot() +
# Plot the scores (samples)
geom_point(data = scores, aes(x = PC1, y = PC2), color = "#0072B2", size = 3) +
geom_text_repel(data = scores, aes(x = PC1, y = PC2, label = sample), color = "#0072B2", size =2) +
# Plot the loadings (variables) as arrows
geom_segment(data = loadings, aes(x = 0, y = 0, xend = PC1*5, yend = PC2*5),
arrow = arrow(length = unit(0.3, "cm")), color = "grey") +
geom_text_repel(data = loadings, aes(x = PC1*5, y = PC2*5, label = variable, color = group), size = 3) +
# Add axis labels and title
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
panel.background = element_blank(), axis.line = element_line(colour = "black")) +
labs(title = "test PCA",
x = paste0("PC1 (", percent_var_PC1, "%)"),
y = paste0("PC2 (", percent_var_PC2, "%)")
)
thanks you, and yes it does accept it. Just changed the line to
geom_text_repel(data = loadings, aes(x = PC1*5, y = PC2*5, label = variable, color = group), size = 3, key_glyph = "point") +
and it worked.