通过 ggplot 2 运行样条曲线时出错

问题描述

我使用 RMS 创建了一个样条图并想整理它,类似于在这个例子中的做法http://rstudio-pubs-static.s3.amazonaws.com/256256_c8c334094db34575a9bbfdd2b686c019.html

然而,虽然我能够创建样条图(见下文),但当我尝试使用与上述链接相同的代码将其传递到 ggplot 时,我收到此错误 Error: `data` must be a data frame,or other object coercible by `fortify()`,not an S3 object with class trellis。我不知道该怎么做,因为这正是上面例子中所做的,并且 dataplot 不能被强制转换为数据帧,因为它是一个网格。为什么我会收到此错误,我该如何补救?

ddist <- datadist(df)
options(datadist='ddist')

k <- with(df,quantile(X,c(.05,0.25,0.50,.75,.95)))

spline_model <- lrm(Y ~ rcs(X,k),data=df)   ###Could add + other variables after ...k)

dataplot <- plot(Predict(spline_model,BMI_NUM,ref.zero=TRUE,fun=exp))

ggplot(dataplot,aes(BMI_NUM,yhat)) +    #####ERROR OCCURS AT THIS LINE
  #  geom_line(colour="Black",linetype="dashed",size=1.5)+
  theme(plot.subtitle = element_text(vjust = 1),plot.caption = element_text(vjust = 1),axis.line = element_line(size = 0.5,linetype = "solid"),panel.grid.major = element_line(colour = "gray98"),axis.title = element_text(size = 15),panel.background = element_rect(fill = "gray99",colour = "white",linetype = "twodash"),plot.background = element_rect(fill = "white")) +
  scale_x_continuous(breaks = seq(15,50,by=2.5),expression(paste("Body Mass Index",",kg/m^{2})))+
  scale_y_continuous(limits = c(0,10),breaks = seq(0,10,by=0.5),"Odds Ratios (95%CI)")+
  labs(caption = NULL)+
  annotate("text",x=20,y=9,parse = TRUE,label="Women",size=5)+
  geom_hline(yintercept =1,linetype="dashed")

作为参考,当我刚运行 dataplot 时,我确实得到了一个很好的样条曲线,所以这不是问题所在。

enter image description here

解决方法

我刚刚想通了。我有 dataplot plot(Predict(spline_model,BMI_NUM,ref.zero=TRUE,fun=exp)),但它应该是 dataplot