繁体   English   中英

将数据从 predict() 值添加到 R 中另一个 plot 的末尾

[英]Adding Data from predict() values to end of another plot in R

我有一个 csv 文件,其中包含 2010-2019 年的人口估计值。 我已经使用predict() function 来估计 2020 年到 2024 年的人口。我如何将这两个图结合到 2020 年开始的位置,而 2019 年在 x 轴上停止? function ggarrange 会是最佳选择吗?

另外,如何将 x-tick 标记更改为在 2020、2021、2022、2023、2024 显示? 它目前只显示 1、2、3、4、5。 我尝试了scale_x_discrete function 但无济于事。

library(ggplot2)
library(tidyr)
library(tidyverse)

pops <- read_csv("nst-est2019-popchg2010_2019.csv")
OK_pops<- filter(pops, NAME == "Oklahoma")
pop_OK <- pivot_longer(OK_pops,
        cols=starts_with("POP"),
        names_to="Year",
        names_prefix = "POPESTIMATE",
        values_to = "Population"
)

options(digits=4)
pop_OK <- transform(pop_OK, Population=as.numeric(Population))
pop_OK <- transform(pop_OK, Year=as.numeric(Year))

str(pop_OK)

ggplot(pop_OK) + geom_point(aes(x=Year, y=Population))
abline(pop_OK)


model <-lm(formula = Population ~ Year, data = pop_OK)
summary(model)
pred <- predict(model, newdata=data.frame(Year=2020:2024))
setNames(pred, 2020:2024)

plot(pred, pch = 16, col = "blue" )
scale_x_discrete(breaks=c("1", "2", "3", "4", "5"),
                  labels=c("2020","2021","2022","2023","2024"))

你需要使用类似这样的 rbind:

new_data <- rbind(pop_ok, pred$fit)

您需要意识到预测 function 具有三列拟合,lwr(下)和 upr(上)为 output。 如果您抓住 fit 列,那么您将失去上下置信区间。

希望这可以帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM