mat
mat

Reputation: 2617

ggplot2 custom legend combining shape and fill

I am trying to combine fill and color in a ggplot2 legend. Because there are several colors for the x axis, it seems logic that ggplot2 do not know which color to pick in the legend.

For exemple:

library(ggplot2)
ggplot(mpg, aes(fl, hwy)) +
    geom_point(aes(color = fl, shape = factor(year), fill = fl)) +
    scale_shape_manual(values = c("circle filled", "circle open"))

enter image description here

My goal would be to manually edit the factor(year) legend to look like this:

enter image description here

I played around the guides() function without success.

Edit:
Values for shape can be found by running vignette("ggplot2-specs").

Upvotes: 2

Views: 1170

Answers (2)

Algebreaker
Algebreaker

Reputation: 118

Ok, so here is a very roundabout way of making it look like the image above. Maybe someone else can come up with a more intuitive version:

ggplot(mpg, aes(fl, hwy)) +
  geom_point(aes(color = fl, shape = factor(year), fill = factor(year))) +
  scale_shape_manual(values = c(16,79), guide = FALSE)  +
  scale_fill_manual("Year", values=c("grey","white"))+
                    guides(fill = guide_legend(override.aes = list(shape = c(21,21),
                                                color = c("black", "black"))))

Output: enter image description here

Upvotes: 0

mischva11
mischva11

Reputation: 2956

you already had the nearly correct answer with the scale_shape_manual. But somehow the "circle filled" argument is invalid. Since i'm not sure where those values can be looked up, i took the values from a table of a similar question (source): enter image description here

so with value 20 and 79 you can get the desired result.

ggplot(mpg, aes(fl, hwy)) +
  geom_point(aes(color = fl, shape = factor(year), fill = fl)) +
  scale_shape_manual(values = c(16,79))

output: enter image description here

Upvotes: 1

Related Questions