0

I have some issues / problems understanding ggplot2 legends / guides. I am trying to create a ggplot with a separate colour legend for a geom_point layer and a fill legend for a geom_polygon layer that contains an outline colour (which I do not want to be shown in a legend). I need points to have different shapes and different colours for specific categories in the data. On top, I need polygons with outlines the same colour as the fill, just with full opacity and these should not show in the colour legend.

I have recreated my issue using the mtcars data set:

library(ggplot2)
library(dplyr)
library(stringr)

data(mtcars)
mtcars$car<-rownames(mtcars)
mtcars$brand<-str_split_fixed(mtcars$car, " ", 2)[,1]
mtcars$cyl<-as.factor(mtcars$cyl)
mtcars$gear<-as.factor(mtcars$gear)
mtcars$country<-'Japan'
mtcars$country[mtcars$brand %in% c("Cadillac","Lincoln","Chrysler",'Dodge',"AMC","Camaro","Pontiac")]<-'US'
mtcars$country[mtcars$brand %in% c("Volvo","Merc","Ferrari",'Fiat',"Ford","Lotus","Maserati",'Porsche','Valiant')]<-'EU'
mtcars$country<-as.factor(mtcars$country)

num_cols<-c('mpg','disp','hp','drat','wt','qsec','vs','am','carb')
pca<-prcomp(mtcars[,num_cols],scale=T,center=T)
mtcars$x<-pca$x[,1]
mtcars$y<-pca$x[,2]

hull_data <- mtcars %>% group_by(country) %>% slice(chull(x, y))
p<-ggplot(data=mtcars,aes_string(x='x',y='y'))
p<-p+geom_point(size=2,aes_string(shape='cyl',colour='gear')) #show shape and colour in legend
p<-p+geom_polygon(data=hull_data,aes_string(fill = 'country',colour='country'),alpha = .4) #show fill, but not the colour in legend
p

At the moment, the colour legend contains both the point colour levels and the polygon outline colour levels, which is not the desired output. Since the plot is constructed within a function, I need to use aes_string (the user passes in the column names for each attribute). Usually, I would simply put the colour for the polygon outside of the aes mapping, but with strings this does not work (hence it is still in aes_string, which triggers a legend). I have tried setting

p<-p+guides(colour=F)

after creating the geom_polygon layer and then adding the geom_point layer, but this adds both colour info for the geom_point and the geom_layer. I could think of a work around assigning fixed columns like:

data$hull<-data[[HULL_COLUMN]])

and then use aes instead of aes_string, but some of the parameters like point colour are optional and it seems dirty to me.

Have you got any suggestion?

Many thanks in advance!

Sacha Viquerat
  • 329
  • 1
  • 3
  • 14
  • Can you provide an example in a reproducible format using which we can reproduce the issue that you are facing? Read about [how to give a reproducible example](http://stackoverflow.com/questions/5963269). – Ronak Shah Mar 08 '21 at 08:59
  • Probably this answer helps you: https://stackoverflow.com/a/56868188/12249019 – yh6 Mar 08 '21 at 10:19

0 Answers0