Skip to content

Instantly share code, notes, and snippets.

@ericnovik
Created March 28, 2017 01:50
Show Gist options
  • Save ericnovik/c754b99874b4018dceeb0e18aac76a9a to your computer and use it in GitHub Desktop.
Save ericnovik/c754b99874b4018dceeb0e18aac76a9a to your computer and use it in GitHub Desktop.
plot_model_pred <-
function(data,
key = NULL,
plot_units = TRUE,
scales_free = TRUE,
x_var_name = NULL,
y_var_name = NULL,
line = TRUE,
col_by_price = FALSE,
plot_80 = FALSE,
plot_50 = TRUE,
mid = 11,
plot_current_price = FALSE) {
if (is.null(key)) {
p <- ggplot(data,
aes(x = eval(parse(text = x_var_name)),
y = eval(parse(text = y_var_name))),
group = factor(prod_key))
if (scales_free)
p <- p + facet_wrap(~ prod_key, scales = "free")
else
p <- p + facet_wrap(~ prod_key)
}
else
p <-
ggplot(filter(data, prod_key == key),
aes(x = eval(parse(text = x_var_name)),
y = eval(parse(text = y_var_name))))
if (col_by_price)
p <- p + geom_point(aes(color = price), size = 2) +
scale_colour_gradient2(
low = "green",
high = "red",
mid = "yellow",
midpoint = mid
)
else {
p <- p + geom_point(size = 0.5, color = "red")
if (x_var_name == "price")
p <-
p + scale_x_continuous(breaks = seq(min(unique(data$price)),
max(unique(data$price)), by = 2))
}
if (plot_80)
if (plot_units)
p <-
p + geom_linerange(aes(ymin = units_q10, ymax = units_q90),
color = "blue",
size = 0.15)
else
# plotting revenue
p <- p + geom_linerange(aes(ymin = rev_q10, ymax = rev_q90),
color = "blue",
size = 0.15)
if (plot_50)
if (plot_units)
p <- p + geom_linerange(
aes(ymin = units_q25, ymax = units_q75),
alpha = 1 / 5,
color = "blue",
size = 2
)
else
# plotting revenue
p <- p + geom_linerange(
aes(ymin = rev_q25, ymax = rev_q75),
alpha = 1 / 5,
color = "blue",
size = 2
)
p <-
p + xlab(x_var_name) + ylab(y_var_name) + theme_minimal() +
theme(axis.text.x = element_text(angle = 90))
if (length(unique(data$prod_key)) > 50)
p <- p + theme(text = element_text(size = 10))
if (plot_current_price)
p <- p + geom_vline(aes(xintercept = current_price),
colour = "blue",
size = 0.1)
if (line)
p <- p + geom_line(size = 0.1)
return(p)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment