Skip to content

Instantly share code, notes, and snippets.

@ryanbthomas
Created March 2, 2021 04:07
Show Gist options
  • Save ryanbthomas/e18c0b5a5a9d8bd2d4a34895e4fb70d8 to your computer and use it in GitHub Desktop.
Save ryanbthomas/e18c0b5a5a9d8bd2d4a34895e4fb70d8 to your computer and use it in GitHub Desktop.
example for alejandro as an example of avoiding dual y-axes
library(tibble)
library(ggplot2)
library(dplyr)
library(tidyr)
sim_years <- 7
start_year <- 2014
report_pattern <- c(0.25, 0.45, 0.55, 0.75, 0.9, 0.95, 1)
paid_pattern <- c(0.1, 0.25, 0.45, 0.68, 0.85, 0.94, 0.98)
# assuming Poisson with lambda = 100, and Lognormal with mu = 7 and sigma = 2
set.seed(11235)
clms_per_year <- rpois(sim_years, lambda = 100)
rep_clms_per_year <- ceiling(rev(report_pattern) * clms_per_year)
calc_pct_paid <- function(yr, n) {
mu <- rev(paid_pattern)[yr]
sd <- 0.05
pmax(0, pmin(1, rnorm(n, mean = mu, sd = sd)))
}
example_data <- tibble(
yr = rep(seq_len(sim_years), times = rep_clms_per_year),
inc = rlnorm(sum(rep_clms_per_year), meanlog = 7, sdlog = 2)
) %>%
group_by(yr) %>%
mutate(
pct_paid = calc_pct_paid(yr, dplyr::n()),
pd = pct_paid * inc,
case = inc - pd,
py = start_year + yr - 1
) %>%
ungroup() %>%
select(py, pd, case, inc)
plot_data <- example_data %>%
group_by(py) %>%
summarise(
cnt = n(),
tot_pd = sum(pd),
tot_case = sum(case),
max_loss = max(pd + case),
.groups = "drop"
)
plot_data_agg_only <- plot_data %>%
select(-max_loss) %>%
pivot_longer(
cols = c("tot_pd", "tot_case"),
names_to = "part",
values_to = "amt"
)
loss_plot <- ggplot(plot_data_agg_only) +
geom_col(aes(x = py, y = amt, fill = part)) +
geom_point(
aes(x = py, y = max_loss),
data = plot_data,
color = "black",
size = 3
) +
geom_linerange(
aes(x = py, ymin = 0, ymax = max_loss),
data = plot_data,
color = "black",
size = 1.5
) +
ylab("Total Loss Amount") +
scale_y_continuous(
expand = expansion(mult = c(0, 0.05)),
labels = function(x) paste0(x/1000, "k")
)+
theme(
axis.title.x = element_blank(),
axis.text.x = element_blank(),
axis.title.y = element_text(size = 16),
legend.position = "none"
)
cnt_plot <- ggplot(plot_data, aes(x = py, y = cnt)) +
geom_point(
color = "blue",
size = 3
) +
geom_line(
aes(x = py, y = cnt),
color = "blue",
size = 1.5
) +
ylab("Claim Count") +
scale_x_continuous(
n.breaks = 7,
expand = expansion(mult = c(0.13, 0.13))) +
theme(
axis.title.y = element_text(size = 16, colour = "blue")
)
#using patchwork
#
library(patchwork)
loss_plot / cnt_plot + plot_layout(heights = c(4, 1), guides = "collect")
@ryanbthomas
Copy link
Author

example

@ryanbthomas
Copy link
Author

upper panel

  • blue is paid
  • orange is case
  • black is max loss

lower panel

reported claim counts.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment