Adding shape-legend to ggplot2

Hi everyone,
I want to graph the average point of cognitive ability across (7) social classes. The average score is of course for the respondents, but I want to plot its average corresponding to both father and respondent social class. For this purpose I wrote the following ggplot2-code:

ggplot(male) + 
stat_summary(aes(x=a_panssec8_dv, y=ability), geom="point", fun.y = "mean", col="black", fill="red", size=5, shape=24) + 
stat_summary(aes(x=c_jbnssec8_dv, y=ability), geom="point", fun.y = "mean", col="black", size=5, shape=5) + 
theme(axis.text.x = element_text(angle = 45, hjust = 1, vjust = 1)) + xlab("Social classes") + ylab("Mean z-score") 

However, I would also like to add the legend for the 2 shapes, The former filled shape (24) for fathers and the second for the respondent. To do so, I was trying to update the code in the following way:

ggplot(male) + 
  stat_summary(aes(x=a_panssec8_dv, y=ability, shape="Father"), geom="point", fun.y = "mean", col="black", fill="red", size=5, shape=24) + 
  stat_summary(aes(x=c_jbnssec8_dv, y=ability, shape="Respondent"), geom="point", fun.y = "mean", col="black", size=5, shape=5) + 
  theme(axis.text.x = element_text(angle = 45, hjust = 1, vjust = 1)) + xlab("Social classes") + ylab("Mean scaled ability") + 
  scale_shape_manual(name="Legend", 
                     labels=c("Father", "Respondent"),
                     values=c(24,5))
  

but still without any success. How can I add the legend?
Thank you all

Maybe the issue comes from defining shape both inside the aes() function and outside of it, if you want to have a legend then just do it inside aes(). Although, I can't test this since you are not providing sample data.

If you need more specific help, please provide a proper REPRoducible EXample (reprex) illustrating your issue.

Yep, it worked. The following code is the final solution for the plot:

ggplot(uk_3) + 
  stat_summary(aes(x=a_panssec8_dv, y=ability, shape="Father"), geom="point", fun.y = "mean", col="red", fill="red",size=5 ) + 
  stat_summary(aes(x=c_jbnssec8_dv, y=ability, shape="Respondent"), geom="point", fun.y = "mean", col="black", size=5) + 
  theme(axis.text.x = element_text(angle = 45, hjust = 1, vjust = 1)) + xlab("Social classes") + ylab("Mean z-score") + 
  scale_shape_manual(name="Legend", 
                     labels=c("Father", "Respondent"),
                     values=c(24, 5))

Thanks!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.