Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

ggplot2

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?

like image 566
neversaint Avatar asked Mar 09 '17 04:03

neversaint


People also ask

How do I delete a specific legend in ggplot2?

By specifying legend. position=”none” you're telling ggplot2 to remove all legends from the plot.

How do I delete a legend?

Tip: To quickly remove a legend or a legend entry from a chart, you can select it, and then press DELETE. You can also right-click the legend or a legend entry, and then click Delete.

How do I remove the legend from a title in R?

To remove legend title, its legend. title attribute is set to element_blank(). Example: Removing legend title with theme().

How do I change the legend value in ggplot2?

You can use the following syntax to change the legend labels in ggplot2: p + scale_fill_discrete(labels=c('label1', 'label2', 'label3', ...))


1 Answers

Set your fill guide to FALSE

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 = FALSE)
like image 50
SymbolixAU Avatar answered Nov 15 '22 01:11

SymbolixAU