ggplot2 errorbar with smooth confidence interval

Viewed 121

I saw the following graph from the coefplot Stata package the other day. I am just wondering how can I draw a similar smooth confidence interval as an errorbar using ggplot? I have tried the geom_errorbar and don't think it is capable to do so. Any other ideas? Thanks!

enter image description here

1 Answers

If you read the stata documentation for smoothed ci plot, it's actually from David Sparks who provided the code here. You just need to alter it slightly to make it side by side.

Below I modified the function from the git link, using ggplot() instead of qplot() :

SmoothCoefficientPlot <- function(models, modelnames = "", removeintercept = FALSE){

  Alphas <- seq(1, 99, 2) / 100
  Multiplier <- qnorm(1 - Alphas / 2)
  zzTransparency <<- 1/(length(Multiplier)/4)
  CoefficientTables <- lapply(models, function(x){summary(x)$coef})
  TableRows <- unlist(lapply(CoefficientTables, nrow))

  if(modelnames[1] == ""){
    ModelNameLabels <- rep(paste("Model", 1:length(TableRows)), TableRows)
    } else {
    ModelNameLabels <- rep(modelnames, TableRows)
    }

  MatrixofModels <- cbind(do.call(rbind, CoefficientTables), ModelNameLabels)
  if(removeintercept == TRUE){
    MatrixofModels <- MatrixofModels[!rownames(MatrixofModels) == "(Intercept)", ]
    }
  MatrixofModels <- data.frame(cbind(rownames(MatrixofModels), MatrixofModels))

  MatrixofModels <- data.frame(cbind(MatrixofModels, rep(Multiplier, each = nrow(MatrixofModels))))

  colnames(MatrixofModels) <- c("IV", "Estimate", "StandardError", "TValue", "PValue", "ModelName", "Scalar")
  MatrixofModels$IV <- factor(MatrixofModels$IV)
  MatrixofModels[, -c(1, 6)] <- apply(MatrixofModels[, -c(1, 6)], 2, function(x){as.numeric(as.character(x))})
  MatrixofModels$Emphasis <- by(1 - seq(0, 0.99, length = length(Multiplier) + 1)[-1], as.character(round(Multiplier, 5)), mean)[as.character(round(MatrixofModels$Scalar, 5))]

  OutputPlot <- ggplot(data = MatrixofModels, aes(x = IV, y = Estimate,
   ymin = Estimate - Scalar * StandardError, ymax = Estimate + Scalar * StandardError,alpha = I(zzTransparency), colour = ModelName)) +
  geom_point(position=position_dodge(width=0.3))
  OutputPlot <- OutputPlot + geom_hline(yintercept = 0, lwd = I(7/12), colour = I(hsv(0/12, 7/12, 7/12)), alpha = I(5/12))
  OutputPlot <- OutputPlot + geom_linerange(aes(size = 1/Emphasis),position=position_dodge(width=0.3),show.legend=FALSE)
  OutputPlot <- OutputPlot + scale_size_continuous()
  OutputPlot <- OutputPlot + coord_flip() + theme_bw()
  return(OutputPlot)
  }

First create two simple linear models with similar coefficients and plot:

library(ggplot2)
mdls = by(mtcars,mtcars$am,function(x)lm(mpg ~ gear + drat + vs,data=x))

enter image description here

Related