簡體   English   中英

具有平滑置信區間的ggplot2誤差條

[英]ggplot2 errorbar with smooth confidence interval

coefplot我從coefplot Stata 包中看到了下圖。 我只是想知道如何使用 ggplot 繪制與誤差條類似的平滑置信區間? 我已經嘗試過geom_errorbar並且認為它沒有能力這樣做。 還有其他想法嗎? 謝謝!

在此處輸入圖片說明

如果您閱讀了平滑 ci 圖的 stata 文檔,它實際上來自David Sparks ,他在這里提供了代碼。 你只需要稍微改變它,讓它並排。

下面我從 git 鏈接修改了函數,使用ggplot()而不是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)
  }

首先創建兩個具有相似系數和繪圖的簡單線性模型:

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

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM