【问题标题】:ggplot2 errorbar with smooth confidence interval具有平滑置信区间的 ggplot2 误差线
【发布时间】:2021-12-22 20:43:31
【问题描述】:

前几天我从coefplot Stata 包中看到了下图。我只是想知道如何使用 ggplot 绘制与误差条类似的平滑置信区间?我已经尝试过geom_errorbar,但认为它不能这样做。还有其他想法吗?谢谢!

【问题讨论】:

    标签: r ggplot2 visualization errorbar


    【解决方案1】:

    如果您阅读统计信息 documentation 以了解平滑 ci 图,它实际上来自提供代码 hereDavid 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))
    

    【讨论】:

    • 太棒了!!非常感谢您的帮助
    猜你喜欢
    • 2014-10-20
    • 2019-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-27
    • 2017-11-20
    • 2021-12-08
    • 2018-01-24
    相关资源
    最近更新 更多