#' Make a simple visualisation for variable stability.
#'
#' @param yVar A logical vector of dependent variable.
#' @param xVar A factor or logical vector of independent variable.
#' @param year A factor for the periods of analysis.
#' @param name A character name of dependent variable only for labels.
#' @param dir A character directory where functions saves the image.
#' @return NULL. Side effect: a plot saved in dir.
#' @examples
#' data(lendclub)
#' # save results to getwd()
#' #plotVarStab(lendclub$loan_status, lendclub$purpose, year=lendclub$issue_d,
#' #dir=getwd(), name = "purpose_loanstatus")
#' #or you can replace a year with other variable to check how it behaves in
#' #such relationship for instance:
#' #plotVarStab(lendclub$loan_status, lendclub$purpose, year=lendclub$grade,
#' #dir=getwd(), name = "purpose_grade")
#' @export
#' @importFrom graphics axis
#' @importFrom graphics barplot
#' @importFrom graphics legend
#' @importFrom graphics lines
#' @importFrom graphics par
#' @importFrom graphics plot
#' @importFrom graphics plot.new
#' @importFrom grDevices graphics.off
#' @importFrom grDevices png
#'
plotVarStab <- function(yVar, xVar, year, name = NA, dir = getwd()){
on.exit(if(is.null(dev.list()) == F){ dev.off()}, add=T)
yearUniq <- sort(unique(year))
xVarUniq <- sort(unique(xVar))
n <- length(xVarUniq)
m <- length(yearUniq)
mBadRate <- matrix(0, nrow = n, ncol = m)
w <- 1
for (i in yearUniq){
idx <- which(year==i)
mBadRate[w : (w + n - 1)] <- getBadRate(yVar = yVar[idx], xVar = xVar[idx])
w <- w + n
}
colnames(mBadRate) <- yearUniq
rownames(mBadRate) <- xVarUniq
# save graphs ---------------------------------------------------------------
png(paste0(dir,"/",name,".png",sep=""),height=1500,width = 1500,pointsize =27)
par(mfrow=c(2,1))
# first plot ------------
plot(mBadRate[,1], type="b", ylim=c(0,1),xaxt="n", ylab="",xlab="", main=name)
axis(1, at=1:n, labels = xVarUniq, las = 2)
for(i in 2:m){
lines(mBadRate[,i], col = i, type = "b")
}
legend("topright", legend = yearUniq, fill = 1:m,
horiz = TRUE, bty = "n", cex = 0.8)
par(xpd = TRUE)
# second plot -----------
colourrrs <- c("red", "orange", "blue", "green", "brown", "black",
"palegreen", "darkblue", "skyblue", "yellow", "grey")
barplot(prop.table(table(xVar, year), margin = 2), col = colourrrs,
main = name, yaxt = "n")
legend(-1.2,1.3, legend = xVarUniq, fill = colourrrs,
horiz=F, bty="n", cex=0.8)
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.