Home > Net >  ggplot points have color but legend (guide) points are all black
ggplot points have color but legend (guide) points are all black

Time:11-10

I have a ggplot where I want to fill points with color based on ID and set shapes based on Group, using shapes 21 and 22, which have an outline color and a 'fill' color. The points in the plot are correct, but the legend or guide on the right has all points shown as black.

Here's a code example:

library(ggplot2)

data <- list()
data[['ID']] <- c("1","1","1","1","2","2","2","2","3","3","3","3")
data[['Group']] <- rep(c("A","B"),6)
data[['x']] <- seq(1:12)
data[['y']] <- log(data[['x']])

df <- data.frame(data)
df

# I want to use point shapes with outlines (shapes 21,22, and 23) assigned 
# to different 'Group' (A or B), outline is set at black.
# Colors are manual filled as red, blue and green based on 'ID' ("1", "2", or "3")
# The problem is the ggplot guide for Color is all black. 
# The guide/legend doesn't reflect the point fill color based on ID.
ggplot(df, aes(x=x, y=y, fill=ID))   
  geom_point(aes(shape=Group, fill=ID), size=6)  
  scale_fill_manual(values = c("1"="red", "2"="blue", "3"="green"))   
  scale_shape_manual(values=c("A"=21,"B"=22))

`

My expectation is that the legend will reflect the point colors. Ggplot shapes 21 and 21 have a fill attribute (can be filled). That means scale_fill_manual is the correct option. I've tried combinations of fill and color at the ggplot level, geom_point call (in aes), but I haven't been able to find the combination that will work. It seems like the legend is taking its color from the outline of the shapes, black (default) in this case.

ggplot scatter plot

CodePudding user response:

guides(fill = guide_legend(override.aes = list(shape=21)))

The issue is that the legend for fill does not "know" that you are using non-default shapes for your points, so we can override the default to make it use shape 21. The enter image description here

  • Related