如何使用ggplot填充回归线下方的图

时间:2019-12-16 01:01:15

标签: r ggplot2 geom-area

我有一个带有回归线的散点图,想填充回归线灰色以下的空间。

#my data
p2 = as.data.frame(cbind(Population = c(1432132, 2582830,1628701, 2278906,476179), Borough =c("BRONX", "BROOKLYN", "MANHATTEN", "QUEENS", "STATEN ISLAND"), count = c(341, 1427, 1092, 700, 39)))

p2$Population = as.numeric(as.character(p2$Population))
p2$count = as.numeric(as.character(p2$count))

fit = lm(p2$count ~ p2$Population , data = p2)

#the plot
ggplot(p2, aes(x=Population, y=count, color = Borough)) +
  geom_point() + 
  geom_text(label=p2$Borough, hjust = -0.1) + 
  geom_smooth(color = "black", method='lm', formula= y~x, se = FALSE) +
  theme_classic()

到目前为止,我已经尝试使用geom_area(aes(fill =)),但是没有将回归用作数据,而是将我的数据点连接到回归线。无论如何,有没有指定填充回归线而不是数据?

1 个答案:

答案 0 :(得分:1)

这应该可以解决问题:

ggplot(p2, aes(x=Population, y=count)) +
  geom_point() +
  geom_text(label=p2$Borough, hjust = -0.1) + 
  geom_smooth(color = "black", method='lm', formula= y~x, se = F) +
  geom_ribbon(aes(ymin = 0,ymax = predict(lm(count ~ Population))),
              alpha = 0.3,fill = 'green')+
  theme_classic()