线性对数回归模型的ggplot?

时间:2021-04-27 10:55:50

标签: r

如何在 R 中绘制对数线性模型? 目前,我正在这样做,但不确定这是否是正确/有效的方式:

data(food)
model1 <- lm(food_exp~log(income), data = food)
temp_var <- predict(model1, interval="confidence")
new_df <- cbind(food, temp_var)
head(new_df)
ggplot(new_df, aes(x = income, y = food_exp))+
  geom_point() +
  geom_smooth(aes(y=lwr), color = "red", linetype = "dashed")+
  geom_smooth(aes(y=upr), color = "red", linetype = "dashed")+
  geom_smooth(aes(y = fit), color = "blue")+
  theme_economist()

2 个答案:

答案 0 :(得分:1)

你可以使用 geom_smooth 并直接输入你的公式。它应该产生与你的拟合相同的结果(你也可以通过绘制来检查)

ggplot(new_df, aes(x = Sepal.Width, y = Sepal.Length))+
  geom_point() +
  geom_point(aes(y=fit), color="red") + #your original fit
  geom_smooth(method=lm, formula=y~log(x)) #ggplot fit

答案 1 :(得分:0)

如果你不关心提取参数,只想要绘图,你可以直接在ggplot2中绘图。

一些用于绘图的假数据:

library(tidyverse)

set.seed(454)
income <- VGAM::rpareto(n = 100, scale = 20, shape = 2)*1000
food_exp <- rnorm(100, income*.3+.1, 3)

food <- data.frame(income, food_exp)

现在在 ggplot2 中,使用 geom_smooth 函数并指定您想要一个线性模型。此外,您可以直接在 aes 参数中转换收入:

ggplot(food, aes(x = log(income), y = food_exp))+
  geom_point()+
  geom_smooth(method = "lm")+
  theme_bw()+
  labs(
    title = "Log Linear Model Food Expense as a Function of Log(income)",
    x = "Log(Income)",
    y = "Food Expenses"
  )

Desired graph of log of income vs expenses

这适用于置信区间,但添加预测区间,您需要按照之前所做的来拟合模型,生成预测区间。