R 在ggplot中映射残差时添加图例

R 在ggplot中映射残差时添加图例,r,ggplot2,legend,ggmap,R,Ggplot2,Legend,Ggmap,我一直在尝试为残差添加一个图例,但不知道在何处放置代码以使其工作 这是残差图,但没有图例: ggplot(lat_long, aes(lat_long$INTPTLON10, lat_long$INTPTLAT10)) + geom_polygon(data = states, aes(x=long, y = lat, group = group), color= "darkgray", fill="gray") + coord_fixed(1.3)+ #keeps the aspe

我一直在尝试为残差添加一个图例,但不知道在何处放置代码以使其工作

这是残差图,但没有图例:

ggplot(lat_long, aes(lat_long$INTPTLON10, lat_long$INTPTLAT10)) + 
  geom_polygon(data = states, aes(x=long, y = lat, group = group), color= "darkgray", fill="gray") + 
  coord_fixed(1.3)+ #keeps the aspect ratio 
  geom_point(col=c("blue", "red")[sign(full_resid)/2+1.5], #assigns color of dots if +/- residual
             pch=19,cex=abs(full_resid), #assigns size of dots
             show.legend = T) + #can't figure out how to create the legend
  theme_map()


蓝色点为负残差,红色点为正残差。大小是残差的大小。也许没有必要使用两种不同的颜色,但是使用图例显示点的大小可能会有所帮助

提前谢谢你! 编辑:这是数据!(如果这不是分享的最佳方式,请告诉我)


要获得颜色和大小的图例,需要将它们映射到美学,然后在比例函数中设置颜色。大概是这样的:

ggplot(lat_long, aes(INTPTLON10, INTPTLAT10)) + 
  geom_polygon(data = states, aes(x=long, y = lat, group = group), color= "darkgray", fill="gray") + 
  coord_fixed(1.3)+
  geom_point(aes(color=resid(best)>3, size=abs(resid(best))),
             pch=19) +
  scale_color_manual(values=c('red', 'blue')) +
  theme_map()

谢谢你的回复!我对R相当陌生,所以我非常感谢你的帮助。当我运行你的代码时,我得到了一个错误,上面写着:“错误:一个连续变量不能映射到形状”,如果你可以发布一个有帮助的数据选择。只需添加数据!我不确定我是否做对了。再次感谢您的帮助!我确实添加了括号,但不幸的是它仍然不起作用。我还更新了代码以反映文件名的更改。哪里是
状态
来源?
ggplot(lat_long, aes(INTPTLON10, INTPTLAT10)) + 
  geom_polygon(data = states, aes(x=long, y = lat, group = group), color= "darkgray", fill="gray") + 
  coord_fixed(1.3)+
  geom_point(aes(color=resid(best)>3, size=abs(resid(best))),
             pch=19) +
  scale_color_manual(values=c('red', 'blue')) +
  theme_map()