neversaint
neversaint

Reputation: 63984

How do I just remove one of the two legends in GGPLOT

I have the following code:

library(ggplot2)

df     <- data.frame(iris)                   # iris dataset
pca    <- prcomp(df[,1:4], retx=T, scale.=T) # scaled pca [exclude species col]
scores <- pca$x[,1:3]                        # scores for first three PC's

# k-means clustering [assume 3 clusters]
km     <- kmeans(scores, centers=3, nstart=5)
ggdata <- data.frame(scores, Cluster=km$cluster, Species=df$Species)

# stat_ellipse is not part of the base ggplot package
source("https://raw.githubusercontent.com/tidyverse/ggplot2/master/R/stat-ellipse.R")


ggplot(ggdata) +
  geom_point(aes(x=PC1, y=PC2, color=factor(Species)), size=5, shape=20) +
  stat_ellipse(aes(x=PC1,y=PC2,fill=factor(Species)),
               geom="polygon", level=0.95, alpha=0.2) +
  guides(color=guide_legend("Species"),fill=guide_legend("Cluster"))

Which produces this:

enter image description here

As stated in that picture how do I just remove 'Cluster' legend?

Upvotes: 14

Views: 12966

Answers (1)

SymbolixAU
SymbolixAU

Reputation: 26248

Set your fill guide to "none"

 ggplot(ggdata) +
   geom_point(aes(x=PC1, y=PC2, color=factor(Species)), size=5, shape=20) +
     stat_ellipse(aes(x=PC1,y=PC2, fill=factor(Species)),
                                 geom="polygon", level=0.95, alpha=0.2)+
      guides(color=guide_legend("Species"), fill = "none")

Edit: 20221129 - changed scale = FALSE to scale = "none", as per:

The <scale> argument of guides() cannot be FALSE. Use "none" instead as of ggplot2 3.3.4.

Upvotes: 21

Related Questions