如何在 R 中使用 ggplot2 将图例添加到分布图

How to add legend to distribution plot with ggplot2 in R

我想绘制一个负二项分布和一个泊松分布来拟合我的真实数据,但我不知道如何绘制图例,谁能帮助我,非常感谢。我的代码和图片如下:

ggplot() + 
  geom_density(aes(a),color="red",lwd=2) + 
  geom_density(aes(x=rpois(50,1.57)),color="purple",lwd=2) + 
  geom_smooth() + 
  geom_density(aes(x=rnbinom(100,size=0.2,mu=1.57)),color="blue",lwd=2) + 
  geom_smooth() + 
  coord_cartesian(xlim=c(0,10)) + labs(x="count")

我的数据上传到这里: https://www.jianguoyun.com/p/DSHXKgMQm5CLBhiKjCc.

添加图例的最简单方法是将变量映射到颜色。例如

ggplot() + 
  geom_density(aes(a, color="data"),lwd=2) + 
  geom_density(aes(x=rpois(50,1.57), color="poisson"),,lwd=2) + 
  geom_smooth() + 
  geom_density(aes(x=rnbinom(100,size=0.2,mu=1.57),color="binomial"),lwd=2) + 
  geom_smooth() + 
  coord_cartesian(xlim=c(0,10)) + labs(x="count")