如何使用ggplotfacet_wrap

问题描述 投票:0回答:1

和结果图:

ggplot facet_wrap中的任何新开发都以添加每个Facet图的单独X轴标题?因此,我可以在包装器函数中传递一些标记参数:histogram1 plot_hist_all <- plot_histograms(data = R_macro_rev, columns = 7:15, rename_vars = c("N" = "Total N", "P" = "Total P", "K" = "Total K", "Ca" = "Total Ca", "Mg" = "Total Mg","NP" = "N:P", "NK" = "N:K", "PK" = "P:K", "CaMg" = "Ca:Mg"), # rename the stoichiometric vars rename_xlab = c("N" = "Total N (mg/kg)", "P" = "Total P (mg/kg)", "K" = "Total K (mg/kg)", "Ca" = "Total Ca (cmol(+)/kg)", "Mg" = "Total Mg (cmol(+)/kg)", "NP" = "N:P", "NK" = "N:K", "PK" = "P:K", "CaMg" = "Ca:Mg")) plot_hist_all

我使用了注释方法,但是必须手动设置它,并且不能自动适合正确的x轴位置,如这样:

hist2使用拼布的方法。更多手册。仍在等待facet_wrap方法。

library(ggplot2) library(dplyr) library(tidyr) library(patchwork) windowsFonts(Palatino = windowsFont("Palatino Linotype")) plot_histograms_patchwork <- function(data, columns = where(is.numeric), rename_xlab = NULL) { # Select columns properly selected_cols <- if (is.numeric(columns)) { names(data)[columns] # Select by index } else { names(select(data, {{ columns }})) # Select by condition (e.g., numeric) } plots <- list() # Store individual plots for (col in selected_cols) { x_label <- if (!is.null(rename_xlab) && col %in% names(rename_xlab)) rename_xlab[[col]] else "Value" # Conditional y-axis title only for "Ca" y_label <- if (col == "Ca") "Frequency" else NULL p <- ggplot(data, aes(x = .data[[col]])) + geom_histogram(aes(y = after_stat(count)), bins = 30, fill = "#69b3a2", color = "#e9ecef", alpha = 0.9, na.rm = TRUE) + theme_bw() + theme( text = element_text(family = "Palatino"), axis.title.x = element_text(size = 12), axis.title.y = if (col == "Ca") element_text(size = 12) else element_blank(), plot.title = element_blank() # Remove titles ) + labs(x = x_label, y = y_label) plots <- append(plots, list(p)) } # Arrange all plots using patchwork with 3 columns final_plot <- wrap_plots(plots) + plot_layout(ncol = 3) return(final_plot) } plot_hist_all <- plot_histograms_patchwork( data = R_macro_rev, columns = 7:15, rename_xlab = c("N" = "Total N (mg/kg)", "P" = "Total P (mg/kg)", "K" = "Total K (mg/kg)", "Ca" = "Total Ca (cmol(+)/kg)", "Mg" = "Total Mg (cmol(+)/kg)", "NP" = "N:P ", "NK" = "N:K ", "PK" = "P:K ", "CaMg" = "Ca:Mg ") ) plot_hist_all
r ggplot2 facet-wrap x-axis
1个回答
0
投票

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.