stRoke/R/plot_olr.R

66 lines
2.2 KiB
R
Raw Normal View History

2022-09-23 12:05:32 +02:00
utils::globalVariables(c("or","ord","lo","up"))
2022-09-26 13:59:05 +02:00
#' Forest plot from ordinal logistic regression.
2022-09-22 19:53:15 +02:00
#'
#' Heavily inspired by https://www.r-bloggers.com/plotting-odds-ratios-aka-a-forrestplot-with-ggplot2/
#'
#' @param x input data.
#' @param title plot title
#' @param dec decimals for labels
2022-09-26 13:59:05 +02:00
#' @param lbls labels for variable names. Careful, as the right order is not checked automatically!
2022-09-22 19:53:15 +02:00
#' @param hori labels the horizontal axis (this i the y axis as the plot is rotated)
#' @param vert labels the horizontal axis (this i the x axis as the plot is rotated)
#' @param short flag to half number of ticks on horizontal axis.
2022-09-26 13:59:05 +02:00
#' @param input can be either "model", which is a olr model (polr()), or "df", which is a data frame with three columns for OR, lower CI and upper CI.
2022-09-22 19:53:15 +02:00
#'
#' @return gg object
2022-09-23 09:14:47 +02:00
#' @keywords forest plot
#'
2022-10-11 08:25:39 +02:00
#' @import ggplot2 stats
#'
#' @importFrom MASS polr
2022-09-23 12:05:32 +02:00
#'
2022-09-22 19:53:15 +02:00
#' @export
2022-09-23 09:14:47 +02:00
#'
#' @examples
2022-09-23 12:05:32 +02:00
#' iris$ord<-factor(sample(1:3,size=nrow(iris),replace=TRUE),ordered=TRUE)
#' lm <- MASS::polr(ord~., data=iris, Hess=TRUE, method="logistic")
#' plot_olr(lm, input="model")
2022-09-22 19:53:15 +02:00
2022-09-23 12:05:32 +02:00
plot_olr<-function(x, title = NULL, dec=3, lbls=NULL, hori="OR (95 % CI)", vert="Variables", short=FALSE, input=c("model","df")){
2022-09-22 19:53:15 +02:00
if (input=="model"){
2022-09-23 12:05:32 +02:00
odds <- data.frame(cbind(exp(coef(x)), exp(confint(x))))
2022-09-22 19:53:15 +02:00
}
if (input=="df"){
2022-09-23 12:05:32 +02:00
odds <- x
2022-09-22 19:53:15 +02:00
}
names(odds)<-c("or", "lo", "up")
2022-09-23 12:05:32 +02:00
rodds<-round(odds, digits = dec)
2022-09-22 19:53:15 +02:00
if (!is.null(lbls)){
odds$vars<-paste0(lbls," \n",paste0(rodds$or," [",rodds$lo,":",rodds$up,"]"))
2022-09-23 12:05:32 +02:00
} else {
2022-09-22 19:53:15 +02:00
odds$vars<-paste0(row.names(odds)," \n",paste0(rodds$or," [",rodds$lo,":",rodds$up,"]"))
}
ticks<-c(seq(0, 1, by =.1), seq(1, 10, by =1), seq(10, 100, by =10))
if (short==TRUE){
ticks<-ticks[seq(1, length(ticks), 2)]
}
odds$ord<-c(nrow(odds):1)
2022-09-23 12:05:32 +02:00
odds|>
ggplot2::ggplot(mapping = ggplot2::aes(y = or, x = reorder(vars,ord))) +
ggplot2::geom_point() +
ggplot2::geom_errorbar(mapping = ggplot2::aes(ymin=lo, ymax=up), width=.2) +
ggplot2::scale_y_log10(breaks=ticks, labels = ticks) +
ggplot2::geom_hline(yintercept = 1, linetype=2) +
ggplot2::coord_flip() +
ggplot2::labs(title = title, x = vert, y = hori) +
ggplot2::theme_bw(14)
2022-09-22 19:53:15 +02:00
}