Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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)))

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading