How to add circle on ggbiplot plot using geom_encircle from ggalt package?

371 Views Asked by At

Recently, I used ggbiplot package to draw the PCA plot.

For better visualization, I also added geom_encircle to get circle region on the PCA result.

How, the problem I met is I don't know how to get the mapping color consistently.

I tried several methods but didn't work.

Here is my example code, and you can see, the color of these points and the regions are not the same. So who could give me some advice or solution.

Very thankful.

library(ggalt)
library(ggbiplot)
data(wine)
wine.pca$x
table(wine.class)
wine.pca <- prcomp(wine, scale. = TRUE)
ggbiplot(wine.pca, obs.scale = 1, var.scale = 1,
         groups = wine.class, ellipse = F, circle = F) +
  # scale_color_discrete(name = '') +
  theme(legend.direction = 'horizontal', legend.position = 'top')+
  geom_point(aes(color = wine.class), size = 1) +
  scale_color_manual(name="Saturday",values=c("red","green","blue"))+
  
  geom_encircle(aes(group=wine.class,fill=c(rep("red",59),
                                                   rep("green",71),
                                                   rep("blue",48))), alpha = 0.3, show.legend = F,colour=NA)
1

There are 1 best solutions below

3
On

You could achieve your desired result by mapping wine.class on the fill aes. To apply the same palette to color and fill I added aesthetics = c("color", "fill") to scale_color_manual:

library(ggalt)
library(ggbiplot)
data(wine)

wine.pca <- prcomp(wine, scale. = TRUE)

ggbiplot(wine.pca,
  obs.scale = 1, var.scale = 1,
  groups = wine.class, ellipse = F, circle = F
) +
  theme(legend.direction = "horizontal", legend.position = "top") +
  geom_point(aes(color = wine.class), size = 1) +
  scale_color_manual(name = "Saturday", values = c("red", "green", "blue"), aesthetics = c("color", "fill")) +
  geom_encircle(aes(fill = wine.class), alpha = 0.3, show.legend = F, colour = NA)