用置信区间绘制predict.lm结果

时间:2017-11-24 14:28:42

标签: r plot linear-regression

我有一个df,其predict.lm的输出附加到另一个df,其中包含两列labelactual

df <- data.frame(
label = c('A', 'B', 'C', 'D', 'E', 'F', 'G'), 
actual = c(13.9, 13.4, 13.8, 14.3, 14.2, 13.6, 14.1),
fit = c(13.8, 13.9, 14.1, 14.0, 13.9, 14.3, 14.1),
lwr = c(13.6, 13.7, 13.8, 13.8, 13.7, 14.0, 13.9),
upr = c(14.3, 14.2, 14.7, 14.3, 14.1, 14.9, 14.9)
)

我想绘制actualfit的关系,其中lwrupr的显示类似于下图中没有该行,并且这些点可以是基于颜色或基于图案的在label列上。 这个图是我想要我的形象的一个例子。 x和y不是来自我的数据。 plot

2 个答案:

答案 0 :(得分:2)

这样的东西?

library(ggplot2)

df <- data.frame(
  label = c('A', 'B', 'C', 'D', 'E', 'F', 'G'), 
  actual = c(13.9, 13.4, 13.8, 14.3, 14.2, 13.6, 14.1),
  fit = c(13.8, 13.9, 14.1, 14.0, 13.9, 14.3, 14.1),
  lwr = c(13.6, 13.7, 13.8, 13.8, 13.7, 14.0, 13.9),
  upr = c(14.3, 14.2, 14.7, 14.3, 14.1, 14.9, 14.9)
)

ggplot(df, aes(x = actual, y = fit)) +
  theme_bw() +
  geom_ribbon(aes(ymin = lwr, ymax = upr), alpha = 0.5) +
  geom_line(color = "blue") +
  geom_point(aes(color = label))

enter image description here

答案 1 :(得分:1)

您可以使用plot绘制线条,然后使用polygon创建阴影区域。

ORD = order(df$actual)
plot(df[ORD, 2:3],type="l", ylim=c(min(df$lwr), max(df$upr)), col="blue")
polygon(c(df$actual[ORD], df$actual[rev(ORD)]), border=NA,
    c(df$upr[ORD], df$lwr[rev(ORD)]), col="#88888844")

Plot with error limits

如果您想要更流畅的版本,可以使用样条线。

## Smoothed version
plot(spline(df[ORD, 2:3]), type="l", 
    ylim=c(min(df$lwr), max(df$upr)), col="blue")

UpperFun = splinefun(df[ORD, c(2,5)])
LowerFun = splinefun(df[ORD, c(2,4)])
ACT      = seq(min(df$actual), max(df$actual), 0.02)
UPP      = UpperFun(ACT)
LOW      = LowerFun(ACT)

polygon( c(ACT, rev(ACT)), c(UPP, rev(LOW)), 
    border=NA, col="#88888844")

Smoothed curve