使用ggplot绘制逆回归曲线

时间:2018-10-01 05:20:56

标签: r ggplot2

我正在尝试将两条回归线绘制到同一散点图上。看起来我使用ggplot几乎正确。我有一个拟合,使用二阶项,而另一个拟合是小时的倒数是因变量,而个案的倒数是预测变量。数据如下:

df <- read.table(textConnection(
  'hours cases
   1275 230
  1350 235
  1650 250
  2000 277
  3750 522
  4222 545
  5018 625
  6125 713
  6200 735
  8150 820
  9975 992
  12200 1322
  12750 1900
  13014 2022
  13275 2155
  '), header = TRUE)

我有以下内容,但逆回归拟合似乎不合时宜。可以进行哪些调整以获得正确的曲线?我知道曲线应该向上凹并逐渐增加。

ggplot(df, aes(x = cases, y = hours)) +
  geom_point(shape=21, size=3.2,fill="green",color="black")+
  geom_smooth(span=.4,method="lm",formula=y~x+I(x^2))+
  geom_smooth(span=.4,method="lm",formula=I(1/y)~I(1/x))

enter image description here

作为参考,只是y的预测值与x的散点图,其中,y轴是1 / y的预测值的倒数,我们得到

enter image description here

用于生成此代码的代码是

fit<-lm(I(1/hours)~I(1/cases),data=df)
summary(fit)

hw <- theme(
  plot.title=element_text(hjust=0.5,face='bold'),
  axis.title.y=element_text(angle=0,vjust=.5,face='bold'),
  axis.title.x=element_text(face='bold'),
  plot.subtitle=element_text(hjust=0.5),
  plot.caption=element_text(hjust=-.5),
  strip.text.y = element_blank(),
  strip.background=element_rect(fill=rgb(.9,.95,1),
                                colour=gray(.5), size=.2),
  panel.border=element_rect(fill=FALSE,colour=gray(.70)),
  panel.grid.minor.y = element_blank(),
  panel.grid.minor.x = element_blank(),
  panel.spacing.x = unit(0.10,"cm"),
  panel.spacing.y = unit(0.05,"cm"),

  axis.ticks=element_blank(),
  axis.text=element_text(colour="black"),
  axis.text.y=element_text(margin=margin(0,3,0,3)),
  axis.text.x=element_text(margin=margin(-1,0,3,0)),
  panel.background = element_rect(fill = "gray")
)

ggplot(df,aes(x=cases,y=1/fitted(fit))) +
  geom_point(shape=21, size=3.2,fill="green",color="black")+
  labs(x="Surgical Cases",
       y="Predicted Worker Hours",
       title="Predicted Worker Hours vs Surgical Cases")+hw

2 个答案:

答案 0 :(得分:2)

这应该使您入门。包括置信区间将需要额外的工作(例如,计算ggplot2之外的置信带的值)。我将其留给读者练习。

fit2 <- lm(I(1/hours)~I(1/cases), data = df)

ggplot(df, aes(x = cases, y = hours)) +
  geom_point(shape=21, size=3.2,fill="green",color="black")+
  geom_smooth(span=.4,method="lm",formula=y~x+I(x^2), aes(color = "polyn"))+
  stat_function(fun = function(x) 1 / predict(fit2, newdata = data.frame(cases = x)), 
                aes(color = "inv-inv"), size = 1)

resulting plot

答案 1 :(得分:0)

正如@Roland所说,您需要绘制实际模型。

但是,问题是geom_smooth的公式参数不喜欢公式。因此,即使下面的公式正确,它也不会画出正确的线。

使用summary(fit)得到a(-0.00005507)和b(0.1743),直线的截距和斜率:

SELECT CONCAT(FIRST_NAME,',',LAST_NAME) as full_name FROM EMPLOYEES;
相关问题