# Bopbun original example. Code: CC0-1.0.
# Tested: R 4.5.3, ggstats 0.14.0, ggplot2 4.0.4, patchwork 1.3.2.
library(ggplot2)
library(ggstats)
library(patchwork)

answers <- c("Strongly disagree", "Disagree", "Neutral",
             "Agree", "Strongly agree", "No answer")
counts <- list(
  Access = c(10, 15, 20, 25, 26, 4),
  Cost = c(8, 15, 24, 30, 17, 6),
  Timing = c(20, 18, 20, 20, 20, 2)
)
survey <- as.data.frame(lapply(counts, function(n) {
  factor(rep(answers, times = n), levels = answers)
}))
# Every question has 100 responses, including the side category.
stopifnot(all(vapply(counts, sum, numeric(1)) == 100))
side_share <- vapply(survey, function(x) mean(x == "No answer"), numeric(1))
stopifnot(max(side_share) < 0.2)

p <- gglikert_side(
  survey, side_values = "No answer", add_totals = FALSE,
  labels_hide_below = 0.07, labels_size = 3, labels_accuracy = 1
) & theme_minimal(base_size = 10)
p[[1]] <- p[[1]] + theme(legend.position = "bottom") +
  guides(fill = guide_legend(nrow = 2))
p[[2]] <- p[[2]] + labs(title = "No answer") + theme(axis.text.y = element_blank(),
                         axis.ticks.y = element_blank(), legend.position = "none")

before <- p + plot_annotation(
  title = "Synthetic survey: default side axis",
  caption = "100 responses per question; No answer is included in the denominator."
)

# In ggstats 0.14.0, component 2 is the side plot.
# Give the 2-6% side values room, and use just three tick positions.
fixed <- p
fixed[[1]] <- fixed[[1]] + coord_cartesian()
fixed[[2]] <- fixed[[2]] + scale_x_continuous(
  limits = c(0, 0.2), breaks = c(0, 0.1, 0.2),
  labels = scales::label_percent(accuracy = 1),
  expand = expansion(mult = c(0, 0.05))
) + coord_cartesian() + geom_text(
  data = data.frame(question = names(side_share), share = unname(side_share)),
  aes(x = share, y = question, label = scales::percent(share, accuracy = 1)),
  inherit.aes = FALSE, hjust = -0.3, size = 3, colour = "black"
)
fixed <- fixed + plot_layout(widths = c(4, 1))
after <- fixed + plot_annotation(
  title = "Synthetic survey: explicit side axis and panel widths",
  caption = "100 responses per question; No answer is included in the denominator."
)

dir.create("likert-output", showWarnings = FALSE)
for (name in c("before", "after")) {
  ggsave(file.path("likert-output", paste0(name, ".png")),
         plot = get(name), width = 180, height = 100, units = "mm",
         dpi = 300, device = "png", bg = "white")
}
ggsave("likert-output/after.pdf", plot = after,
       width = 180, height = 100, units = "mm", device = "pdf")
write.csv(data.frame(Response = answers, counts),
          "likert-output/counts.csv", row.names = FALSE)
print(side_share)
sessionInfo()
