Skip to content

Instantly share code, notes, and snippets.

@selva86

selva86/ks_plot.R

Last active Jul 7, 2020
Embed
What would you like to do?
Function to create KS Plot using InformationValue R package
require(ggplot2)
ks_table <- InformationValue:::ks_table
ks_plot <- function (actuals, predictedScores) {
rank <- 0:10
ks_table_out <- ks_table(actuals = actuals, predictedScores = predictedScores)
perc_events <- c(0, ks_table_out$cum_perc_responders) * 100
perc_nonevents <- c(0, ks_table_out$cum_perc_non_responders) * 100
random_prediction <- seq(0, 100, 10)
df <- data.frame(rank, random_prediction, perc_events, perc_nonevents)
df_stack <- stack(df, c(random_prediction, perc_events, perc_nonevents))
df_stack$rank <- rep(rank, 3)
df_stack$delta <- df_stack$values[12:22] - df_stack$values[1:11]
values <- df_stack$values
ind <- df_stack$ind
rowmax <- which.max(ks_table_out$difference)
l_start <- ks_table_out[rowmax, "cum_perc_non_responders"]
l_end <- ks_table_out[rowmax, "cum_perc_responders"]
print(ggplot2::ggplot(df_stack, aes(x = rank, y = values,
colour = ind, label = paste0(round(values, 2), "%"))) +
geom_line(size = 1.00) +
labs(x = "rank", y = "Percentage events (1's) & non-events (0's) Captured",
title = "KS Plot", subtitle=paste("KS Statistic: ", InformationValue::ks_stat(actuals, predictedScores))) +
theme(plot.title = element_text(size = 20,
face = "bold")) +
geom_text(aes(y = values + 4), size=2) +
scale_x_continuous(breaks=0:10, labels=0:10) +
geom_segment(x = rowmax, y = l_start*100, xend = rowmax, yend = l_end*100, col="red", arrow = arrow(length = unit(0.05, "npc"), ends="both"), linetype = "dashed", lwd=.5)) +
scale_color_discrete(name="") + theme(legend.justification=c(.99,0.01), legend.position=c(.99,0.01))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.