friendly / ggbiplot

A ggplot2 based biplot for principal components-like methods
https://friendly.github.io/ggbiplot/
10 stars 0 forks source link

scale_color_discrete() produces two legends #2

Open friendly opened 1 year ago

friendly commented 1 year ago

There is something wrong in the code concerning legends for groups when you try to use scale_color_discrete() to set a property. This has to do with the use of color and fill in geom_polygon().

The following example produces two legends:

data(wine)
wine.pca <- prcomp(wine, scale. = TRUE)
ggbiplot(wine.pca, obs.scale = 1, var.scale = 1,
  groups = wine.class, ellipse = TRUE, circle = TRUE) +
  scale_color_discrete(name = '') +
  theme(legend.direction = 'horizontal', legend.position = 'top')

See the result at: https://github.com/friendly/ggbiplot/blob/master/man/figures/README-wine-biplot-1.png

friendly commented 12 months ago

Not a bug. Need to have the same name for aesthetics to be merged.

The following work:

  scale_fill_discrete(name = 'Species') +
  scale_color_discrete(name = 'Species') +

or,

  labs(fill = "Species", color = "Species") +
corybrunson commented 3 weeks ago

I think this is the kind of hassle that drove a quiet API change in {ggplot2}, decided here. The duplication can also be relaxed by using the then-newly exposed aesthetics argument:

library(ggbiplot)
#> Loading required package: ggplot2
data(wine)
wine.pca <- prcomp(wine, scale. = TRUE)
ggbiplot(wine.pca, obs.scale = 1, var.scale = 1,
         groups = wine.class, ellipse = TRUE, circle = TRUE) +
  scale_color_discrete(name = 'Species', aesthetics = c('color', 'fill')) +
  theme(legend.direction = 'horizontal', legend.position = 'top')

Created on 2024-08-21 with reprex v2.1.0

friendly commented 3 weeks ago

Good point. I'll mention this somewhere in the documentation.