Finbar
Finbar

Reputation: 3

Why is my GGplot legend not filling with colour?

I'm using this code:

ggplot(all,aes(x=substrate, y=Ca))+
  geom_boxplot(data=weed,aes(colour=species))+
  scale_colour_manual(values="green3",name=NULL,labels="substrate\nmineral content")+
  geom_jitter(position = position_jitter(width = 0.22),
              alpha=0.75, size=3.5,
              aes(fill=species,shape=type))+
  scale_fill_manual(values=c("red","blue","purple","darkorange","darkgrey","orange2","grey2","darkgreen","black"))+
  scale_shape_manual(values=c(24,21,22))+
  labs(y="Ca mg/kg")

to give me this plot:

but as you can see, the legend is not filling.

when I remove the boxplot, giving me the horizontal green lines and then change the fill=species, to colour=species, and the scale_fill_manual to colour it works. So it's something to do with the legend not taking the values from the fill, but I don't know how to fix it.

Upvotes: 0

Views: 59

Answers (1)

Andy Baxter
Andy Baxter

Reputation: 7626

Having looked at other data the problem is that the default shape for a colour legend of a geom_point doesn't have a fill. Change it using guides like so:

library(ggplot2)

mtcars |> 
  ggplot(aes(cyl, wt, fill = factor(gear), shape = factor(carb))) +
  geom_jitter(position = position_jitter(width = 0.22), size = 4) +
  scale_shape_manual(values=c(24,21,22,23,24,25)) +
  guides(fill = guide_legend(override.aes = list(shape = 24)))

Upvotes: 2

Related Questions