Home > OS >  ggplot2 legend is not matching even with manual overrides
ggplot2 legend is not matching even with manual overrides

Time:04-09

I cannot seem to get the legend to match my graph. I have moved the shape and fill outside of the aes, inside the aes. Followed stack overflows on manual overrides and nothing seems to be working.

So, I have four points (visually only three appear: which is fine for my purposes). Two points are a diamond shape with one being green and the other being blue; then two are circles with one being green and the other being blue. So I want there to be four points on the legend filled with the color - so two diamonds: one greeen, one blue. And then two circles: one green and one blue.

The colors and shapes are right on this enter image description here

CodePudding user response:

I dont have enough rep to put this as a comment, but maybe this one helps:

It seems to me that your legend is not even appearing for this code example. This might be because ggplot only creates legends for aesthetic mappings (within the aes function). However every of your geom_point() does only use one data frame with one row and variable level. This is because the geoms do not communicate their data with eachother, since it is defined locally within each geom. You could think about a way to bind all your data frames into a ggplot compatible 'long' format (e.g. with pivot_longer() and bind_rows()), so you only need one geom_line() and one geom_point() which is mapping colour and fill over some kind of group within your data.

The shape of the data you want to provide ggplot to behave as you expect it is following style:

p1 = data.frame(group = c('income','income'), x = c(0, 0.5), y = c(1,0.8))
p2 = data.frame(group = c('size','size'), x = c(0, 0.8), y = c(1,0.25))

dat <- rbind(p1,p2)
ggplot(dat)   geom_point(aes(x = x, y = y, fill = group, shape = group, col = group))   
  geom_line(aes(x=x,y=y, col = group))
  • Related