Last active
May 4, 2025 12:28
-
-
Save baobabprince/15c7ee7dceafcda10556ffd9fdfcce09 to your computer and use it in GitHub Desktop.
add custom x axis with lines to connect the labels
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(ggplot2) | |
library(patchwork) | |
add_custom_xaxis <- function(plot, size_ratio = 6) { | |
plot_build <- ggplot2::ggplot_build(plot) | |
x_scale_type <- class(plot_build$layout$panel_scales_x[[1]])[1] | |
x_data <- plot_build$data[[1]]$x | |
x_label <- p$labels$x | |
# Handle different scale types | |
if (grepl("discrete", x_scale_type)) { | |
# For discrete scales | |
order_levels <- levels(factor(x_data)) | |
if (is.null(order_levels)) { | |
order_levels <- unique(as.character(x_data)) | |
} | |
} else { | |
x_data_rounded <- round(x_data, 2) # Round to 2 decimal places | |
order_levels <- unique(as.character(x_data_rounded)) | |
order_levels <- order_levels[order(as.numeric(order_levels))] | |
} | |
order_levels <- factor(order_levels, levels = order_levels) | |
rev_order_levels <- factor(order_levels, levels = rev(order_levels)) | |
help_table <- data.frame( | |
order_levels = order_levels, | |
rev_order_levels = rev_order_levels, | |
stringsAsFactors = TRUE | |
) | |
leg <- ggplot2::ggplot(help_table, ggplot2::aes(x = order_levels, y = rev_order_levels)) + | |
ggplot2::geom_segment(ggplot2::aes(xend = 0.5, | |
yend = rev_order_levels)) + | |
ggplot2::geom_segment(ggplot2::aes(xend = as.numeric(order_levels), | |
yend = max(as.numeric(rev_order_levels)) + 0.5)) + | |
ggplot2::xlab(x_label) + | |
ggplot2::theme_void() + | |
ggplot2::theme(axis.text.y = ggplot2::element_text()) + | |
ggplot2::theme(axis.title.x = ggplot2::element_text()) + | |
ggplot2::scale_x_discrete() + # Explicitly use discrete scale | |
ggplot2::scale_y_discrete() # Explicitly use discrete scale | |
p <- p + ggplot2::theme(axis.text.x = ggplot2::element_blank(), | |
axis.title.x = ggplot2::element_blank()) | |
final_plot <- patchwork::wrap_plots(p, leg, ncol = 1, heights = c(size_ratio, 1)) | |
return(final_plot) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment