0

我有一个带有回归线的散点图,并且想将回归线下方的空间填充为灰色。

#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=)) 但不是使用回归作为数据,而是将我的数据点连接到回归线。无论如何指定填充回归线而不是数据?

4

1 回答 1

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()
于 2019-12-16T01:29:50.227 回答