0

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)
stefan
  • 90,330
  • 6
  • 25
  • 51
花落思量错
  • 352
  • 1
  • 11

1 Answers1

1

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)

stefan
  • 90,330
  • 6
  • 25
  • 51
  • Wow,very thankful. You help me a lot. – 花落思量错 Nov 19 '22 at 10:59
  • 1
    Wow,very thankful. You help me a lot. It's really cool! I am really curious that if the core code is aesthetics = c("color", "fill") ?? I have never meet this operation that like a miracle. I have a small question that if there is something wrong with my code especially "fill" in geom_encircle? I think it is ok though it didn't work. – 花落思量错 Nov 19 '22 at 11:22
  • Using `aesthetics = c("color", "fill")` is just a small trick. Of course could we have simply added a `scale_fill_manual`with the same spec. In general there is nothing wrong with your code. As you pass the color names directly you could have used `+ scale_fill_identity()` to fix your issue. But in general I would avoid adding the color specs as a vector. And as you see there is no need to do so. Always better to map a column from the dataset on aesthetics. – stefan Nov 19 '22 at 11:33