### Install and Load ggpubr and rstatix Source: https://github.com/kassambara/ggpubr/wiki/Adding-Adjusted-P-values-to-a-GGPlot Installs the ggpubr and rstatix packages from GitHub and loads them into the R session. Ensure devtools is installed. ```r # Install required package devtools::install_github("kassambara/ggpubr") devtools::install_github("kassambara/rstatix") # Load required package library(ggpubr) library(rstatix) ``` -------------------------------- ### Install ggpubr from GitHub Source: https://github.com/kassambara/ggpubr/blob/master/README.md Install the latest development version of ggpubr directly from GitHub using the devtools package. Ensure devtools is installed first. ```r # Install if(!require(devtools)) install.packages("devtools") devtools::install_github("kassambara/ggpubr") ``` -------------------------------- ### Insert Reprex Example Source: https://github.com/kassambara/ggpubr/blob/master/ISSUE_TEMPLATE.md Placeholder for inserting a minimal reproducible example (reprex) when reporting issues or seeking help. ```r # insert reprex here ``` -------------------------------- ### Install and Load ggpubr Package Source: https://context7.com/kassambara/ggpubr/llms.txt Install the ggpubr package from CRAN or GitHub and load it into the R session. ```r install.packages("ggpubr") ``` ```r if(!require(devtools)) install.packages("devtools") devtools::install_github("kassambara/ggpubr") ``` ```r library(ggpubr) ``` -------------------------------- ### Install ggpubr from CRAN Source: https://github.com/kassambara/ggpubr/blob/master/README.md Use this command to install the ggpubr package from the Comprehensive R Archive Network (CRAN). ```r install.packages("ggpubr") ``` -------------------------------- ### Get Session Information Source: https://github.com/kassambara/ggpubr/blob/master/ISSUE_TEMPLATE.md Command to retrieve detailed session information, including package versions, which is useful for debugging and reproducibility. ```r # please paste here the result of devtools::session_info() ``` -------------------------------- ### Combine ggscatter with Publication Theme Source: https://context7.com/kassambara/ggpubr/llms.txt Integrate ggpubr plots with publication themes by passing a theme object to the ggtheme argument. This example uses ggscatter with theme_pubr. ```r ggscatter(mtcars, x = "wt", y = "mpg", color = "cyl", add = "reg.line", ggtheme = theme_pubr(border = TRUE, legend = "bottom")) ``` -------------------------------- ### Get table dimensions with tab_ncol and tab_nrow Source: https://github.com/kassambara/ggpubr/blob/master/NEWS.md Provides `tab_ncol()` and `tab_nrow()` functions to retrieve the number of columns and rows, respectively, from a `ggtexttable` object. ```R tab_ncol(tt) ``` ```R tab_nrow(tt) ``` -------------------------------- ### Apply Classic Theme with Axis Lines Source: https://context7.com/kassambara/ggpubr/llms.txt Apply theme_classic2() to get a classic ggplot theme that includes visible axis lines, suitable for certain publication styles. ```r p + theme_classic2() ``` -------------------------------- ### Load ggpubr and create sample data Source: https://github.com/kassambara/ggpubr/blob/master/README.md Loads the ggpubr package and creates a sample data frame 'wdata' for demonstrating plotting functions. Includes setting a random seed for reproducibility. ```r library(ggpubr) #> Loading required package: ggplot2 # Create some data format # ::::::::::::::::::::::::::::::::::::::::::::::::::: set.seed(1234) wdata = data.frame( sex = factor(rep(c("F", "M"), each=200)), weight = c(rnorm(200, 55), rnorm(200, 58))) head(wdata, 4) ``` -------------------------------- ### Load sample data for box plots Source: https://github.com/kassambara/ggpubr/blob/master/README.md Loads the built-in 'ToothGrowth' dataset and displays the first few rows to prepare for creating box plots. ```r # Load data data("ToothGrowth") df <- ToothGrowth head(df, 4) ``` -------------------------------- ### Create a density plot with mean lines and rug Source: https://github.com/kassambara/ggpubr/blob/master/README.md Generates a density plot for the 'weight' variable, colored and filled by 'sex'. Adds mean lines and a rug plot. Requires the 'wdata' data frame. ```r # Density plot with mean lines and marginal rug # ::::::::::::::::::::::::::::::::::::::::::::::::::: # Change outline and fill colors by groups ("sex") # Use custom palette ggdensity(wdata, x = "weight", add = "mean", rug = TRUE, color = "sex", fill = "sex", palette = c("#00AFBB", "#E7B800")) ``` -------------------------------- ### Prepare ToothGrowth Data Source: https://github.com/kassambara/ggpubr/wiki/Adding-Adjusted-P-values-to-a-GGPlot Prepares the ToothGrowth dataset by converting the 'dose' column to a factor. This is a common preprocessing step before analysis. ```r # Data preparation df <- ToothGrowth df$dose <- as.factor(df$dose) ``` -------------------------------- ### Create Violin Plots with ggviolin Source: https://context7.com/kassambara/ggpubr/llms.txt Generates violin plots showing kernel probability density with optional internal box plots or summary statistics. Requires the ToothGrowth dataset. ```r library(ggpubr) data("ToothGrowth") df <- ToothGrowth # Violin plot with internal box plot ggviolin(df, x = "dose", y = "len", fill = "dose", palette = c("#00AFBB", "#E7B800", "#FC4E07"), add = "boxplot", # Add boxplot inside add.params = list(fill = "white")) # White fill for boxplot # Violin with mean_se and jitter points ggviolin(df, x = "dose", y = "len", color = "dose", palette = "npg", # Nature Publishing Group palette add = c("jitter", "mean_se"), # Multiple additions error.plot = "crossbar", # Crossbar for error trim = FALSE, # Don't trim violin tails width = 0.8) # Add significance comparisons my_comparisons <- list(c("0.5", "1"), c("1", "2"), c("0.5", "2")) ggviolin(df, x = "dose", y = "len", fill = "dose", palette = c("#00AFBB", "#E7B800", "#FC4E07"), add = "boxplot", add.params = list(fill = "white")) + stat_compare_means(comparisons = my_comparisons, label = "p.signif") + stat_compare_means(label.y = 50) ``` -------------------------------- ### Create Density Plots with ggdensity Source: https://context7.com/kassambara/ggpubr/llms.txt Generates density plots with optional mean/median lines and marginal rug marks. Uses generated sample data for weight and sex. ```r library(ggpubr) # Create sample data set.seed(1234) wdata <- data.frame( sex = factor(rep(c("F", "M"), each = 200)), weight = c(rnorm(200, 55), rnorm(200, 58)) ) # Density plot with mean lines and marginal rug ggdensity(wdata, x = "weight", add = "mean", # Add vertical mean line rug = TRUE, # Add marginal rug color = "sex", # Color by group fill = "sex", # Fill by group palette = c("#00AFBB", "#E7B800"), # Custom colors alpha = 0.5) # Transparency # Faceted density plot ggdensity(wdata, x = "weight", add = "median", rug = TRUE, fill = "sex", palette = "jco", facet.by = "sex", # Facet by sex panel.labs = list(sex = c("Female", "Male"))) ``` -------------------------------- ### Create Histograms with Density Overlay using gghistogram Source: https://context7.com/kassambara/ggpubr/llms.txt Generates histograms with optional density curves, mean/median lines, and marginal rug marks. Requires the ggpubr library and a data frame. ```r library(ggpubr) set.seed(1234) wdata <- data.frame( sex = factor(rep(c("F", "M"), each = 200)), weight = c(rnorm(200, 55), rnorm(200, 58)) ) # Histogram with density overlay gghistogram(wdata, x = "weight", add = "mean", # Add mean line rug = TRUE, # Marginal rug fill = "sex", palette = c("#00AFBB", "#E7B800"), add_density = TRUE, # Overlay density curve bins = 30) # Number of bins ``` ```r # Stacked histogram gghistogram(wdata, x = "weight", fill = "sex", palette = "Paired", position = "stack", # Stacked bars alpha = 0.8, add = "median", add.params = list(linetype = "dashed")) ``` ```r # Weighted histogram gghistogram(iris, x = "Sepal.Length", weight = "Petal.Length", # Weight by another variable fill = "Species", palette = "jco") ``` -------------------------------- ### Configure ggpubr to handle non-standard column names Source: https://github.com/kassambara/ggpubr/blob/master/NEWS.md Set the global option `ggpubr.parse.aes` to `FALSE` to prevent `create_aes()` from parsing its input, allowing ggpubr to handle non-standard column names (e.g., 'A-A') without parsing. ```R options(ggpubr.parse.aes = FALSE) ``` -------------------------------- ### Create a histogram with mean lines and rug Source: https://github.com/kassambara/ggpubr/blob/master/README.md Generates a histogram for the 'weight' variable, colored and filled by 'sex'. Adds mean lines and a rug plot. Requires the 'wdata' data frame. ```r # Histogram plot with mean lines and marginal rug # ::::::::::::::::::::::::::::::::::::::::::::::::::: # Change outline and fill colors by groups ("sex") # Use custom color palette gghistogram(wdata, x = "weight", add = "mean", rug = TRUE, color = "sex", fill = "sex", palette = c("#00AFBB", "#E7B800")) ``` -------------------------------- ### Create aesthetic mappings with create_aes Source: https://github.com/kassambara/ggpubr/blob/master/NEWS.md The `create_aes()` function simplifies the creation of aesthetic mappings from a list, making programming with ggplot2 easier. It now defaults to parsing input and supports spaces in column names. ```R create_aes(list(x = "Sepal.Length", y = "Sepal.Width", color = "Species")) ``` -------------------------------- ### Apply Basic Publication Theme Source: https://context7.com/kassambara/ggpubr/llms.txt Apply the basic publication-ready theme to any ggplot object using theme_pubr(). This theme provides clean aesthetics suitable for publications. ```r library(ggpubr) library(ggplot2) p <- ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point(aes(color = factor(cyl))) # Basic publication theme p + theme_pubr() ``` -------------------------------- ### Add summary statistics arguments in ggsummarystats Source: https://github.com/kassambara/ggpubr/blob/master/NEWS.md Introduces `digits` and `table.font.size` arguments to `ggsummarystats()` for customizing the decimal places and text size of the summary table. ```R ggsummarystats(data, x = "dose", y = "len", color = "supp", palette = c("#00AFBB", "#E7B800"), digits = 3, table.font.size = 8) ``` -------------------------------- ### Load and prepare data for bar plots Source: https://github.com/kassambara/ggpubr/blob/master/README.md Loads the built-in 'mtcars' dataset into the 'dfm' data frame, preparing it for bar plot creation. ```r # Load data data("mtcars") dfm <- mtcars ``` -------------------------------- ### Apply Clean Publication Theme Source: https://context7.com/kassambara/ggpubr/llms.txt Use theme_pubclean() for a minimalist publication theme that removes most non-essential elements, focusing on axis lines. ```r p + theme_pubclean() ``` -------------------------------- ### ggline: Simple Line Plot Source: https://context7.com/kassambara/ggpubr/llms.txt Create a basic line plot using ggline with specified x and y aesthetics. ```r library(ggpubr) # Simple line plot df <- data.frame(dose = c("D0.5", "D1", "D2"), len = c(4.2, 10, 29.5)) ggline(df, x = "dose", y = "len") ``` -------------------------------- ### Create Scatter Plots with ggscatter Source: https://context7.com/kassambara/ggpubr/llms.txt Generates scatter plots with options for regression lines, confidence intervals, correlation coefficients, and group ellipses. Requires the ggpubr library and a data frame. ```r library(ggpubr) data("mtcars") df <- mtcars df$cyl <- as.factor(df$cyl) # Scatter plot with regression line and correlation coefficient ggscatter(df, x = "wt", y = "mpg", add = "reg.line", # Add regression line add.params = list(color = "blue", fill = "lightgray"), conf.int = TRUE, # Confidence interval cor.coef = TRUE, # Show correlation coefficient cor.coeff.args = list(method = "pearson", label.x = 3, label.sep = "\n")) ``` ```r # Scatter with groups, ellipses, and mean points ggscatter(df, x = "wt", y = "mpg", color = "cyl", shape = "cyl", palette = c("#00AFBB", "#E7B800", "#FC4E07"), ellipse = TRUE, # Group ellipses ellipse.type = "confidence", # Confidence ellipse ellipse.level = 0.95, mean.point = TRUE, # Show group mean star.plot = TRUE) # Star plot from centroid ``` ```r # Scatter with text labels df$name <- rownames(df) ggscatter(df, x = "wt", y = "mpg", color = "cyl", palette = "jco", label = "name", # Label points repel = TRUE, # Avoid label overlap label.select = list(top.up = 5, top.down = 5)) # Select labels ``` -------------------------------- ### Compute median and quartiles with median_q1q3 Source: https://github.com/kassambara/ggpubr/blob/master/NEWS.md The `median_q1q3()` function computes the sample median along with the 25th and 75th percentiles. It is a wrapper around `median_hilow_()` with `ci = 0.5`. ```R median_q1q3(data$len) ``` -------------------------------- ### Configure hide.ns argument in stat_pvalue_manual Source: https://github.com/kassambara/ggpubr/blob/master/NEWS.md The `hide.ns` argument in `stat_pvalue_manual()` can now accept logical values (TRUE/FALSE) or character values ('p' or 'p.adj') to filter non-significant results based on p-value or adjusted p-values. ```R stat_pvalue_manual(label = "p.adj", hide.ns = "p.adj") ``` -------------------------------- ### Create Box Plots with ggboxplot Source: https://context7.com/kassambara/ggpubr/llms.txt Generates box plots with jittered points, error bars, and statistical comparisons. Requires the ToothGrowth dataset. ```r library(ggpubr) data("ToothGrowth") df <- ToothGrowth # Basic box plot with jitter points colored by group p <- ggboxplot(df, x = "dose", y = "len", color = "dose", palette = c("#00AFBB", "#E7B800", "#FC4E07"), add = "jitter", # Add jittered points shape = "dose") # Shape by group # Add pairwise comparisons with p-values my_comparisons <- list(c("0.5", "1"), c("1", "2"), c("0.5", "2")) p + stat_compare_means(comparisons = my_comparisons) + stat_compare_means(label.y = 50) # Global ANOVA p-value # Box plot with notch and error bars ggboxplot(df, x = "dose", y = "len", fill = "dose", palette = "jco", # Journal of Clinical Oncology palette notch = TRUE, # Notched box plot bxp.errorbar = TRUE, # Add error bars bxp.errorbar.width = 0.2, add = "mean_sd") # Add mean and standard deviation ``` -------------------------------- ### Prepare Data for Plotting Source: https://github.com/kassambara/ggpubr/blob/master/README.md Converts the 'cyl' variable to a factor and adds a 'name' column from row names. Inspects the first few rows of the modified data frame. ```r dfm$cyl <- as.factor(dfm$cyl) dfm$name <- rownames(dfm) head(dfm[, c("name", "wt", "mpg", "cyl")]) ``` -------------------------------- ### Apply Publication Theme with Custom Legend and Labels Source: https://context7.com/kassambara/ggpubr/llms.txt Customize the publication theme by specifying legend position, base font size, and rotating x-axis labels using theme_pubr(). ```r p + theme_pubr(legend = "right", base_size = 14, # Base font size x.text.angle = 45) # Rotate x-axis labels ``` -------------------------------- ### Add borders to ggtexttable elements Source: https://github.com/kassambara/ggpubr/blob/master/NEWS.md Utilize `tab_add_border()`, `tbody_add_border()`, and `thead_add_border()` to add borders to the entire table, table body, or table head, respectively. ```R tab_add_border() ``` ```R tbody_add_border() ``` ```R thead_add_border() ``` -------------------------------- ### Export Plots to PNG with Custom Resolution Source: https://context7.com/kassambara/ggpubr/llms.txt Export arranged plots to PNG format using ggexport. Customize filename, width, height, and resolution (dpi) for high-quality output. ```r ggarrange(bxp, dp, ncol = 2) %>% ggexport(filename = "figure.png", width = 1600, # Width in pixels height = 800, # Height in pixels res = 300) # Resolution (dpi) ``` -------------------------------- ### Perform Statistical Comparisons with stat_compare_means Source: https://context7.com/kassambara/ggpubr/llms.txt Adds statistical comparisons (t-test, Wilcoxon, ANOVA, Kruskal-Wallis) to plots with bracket annotations. Requires ggpubr and data. ```r library(ggpubr) data("ToothGrowth") df <- ToothGrowth # Two group comparison p <- ggboxplot(df, x = "supp", y = "len", color = "supp", palette = "npg", add = "jitter") p + stat_compare_means() # Default: Wilcoxon test p + stat_compare_means(method = "t.test") # t-test ``` ```r # Paired samples ggpaired(df, x = "supp", y = "len", color = "supp", line.color = "gray", line.size = 0.4, palette = "npg") + stat_compare_means(paired = TRUE) ``` -------------------------------- ### Compute median and confidence intervals with median_hilow_ Source: https://github.com/kassambara/ggpubr/blob/master/NEWS.md The `median_hilow_()` function computes the sample median and specified outer quantiles for confidence limits. By default, it uses the 2.5th and 97.5th percentiles (ci = 0.95). ```R median_hilow_(data$len, conf.level = 0.95) ``` -------------------------------- ### Create a box plot with jittered points and custom colors Source: https://github.com/kassambara/ggpubr/blob/master/README.md Generates a box plot of 'len' by 'dose', with points jittered. Colors the boxes and points by 'dose' using a custom palette. Requires the 'df' data frame. ```r # Box plots with jittered points # ::::::::::::::::::::::::::::::::::::::::::::::::::: # Change outline colors by groups: dose # Use custom color palette # Add jitter points and change the shape by groups p <- ggboxplot(df, x = "dose", y = "len", color = "dose", palette =c("#00AFBB", "#E7B800", "#FC4E07"), add = "jitter", shape = "dose") p ``` -------------------------------- ### Cleveland's Dot Plot with Colored Y-Text and Dashed Grids Source: https://github.com/kassambara/ggpubr/blob/master/README.md Creates a Cleveland's dot plot with y-axis text colored by group using 'y.text.col = TRUE'. Applies a dashed grid theme using 'theme_cleveland()'. ```r ggdotchart(dfm, x = "name", y = "mpg", color = "cyl", # Color by groups palette = c("#00AFBB", "#E7B800", "#FC4E07"), # Custom color palette sorting = "descending", # Sort value in descending order rotate = TRUE, # Rotate vertically dot.size = 2, # Large dot size y.text.col = TRUE, # Color y text by groups ggtheme = theme_pubr() # ggplot2 theme )+ theme_cleveland() # Add dashed grids ``` -------------------------------- ### Add titles and footnotes to ggtexttable Source: https://github.com/kassambara/ggpubr/blob/master/NEWS.md Use `tab_add_title()` and `tab_add_footnote()` to incorporate titles and footnotes into `ggtexttable` objects. ```R tab_add_title(title = "Table Title") ``` ```R tab_add_footnote(footnote = "Table footnote") ``` -------------------------------- ### Lollipop Chart Colored by Group Source: https://github.com/kassambara/ggpubr/blob/master/README.md Generates a lollipop chart colored by a grouping variable. Requires the 'ggpubr' package and a data frame. Customize colors with 'palette' and sort with 'sorting'. ```r ggdotchart(dfm, x = "name", y = "mpg", color = "cyl", # Color by groups palette = c("#00AFBB", "#E7B800", "#FC4E07"), # Custom color palette sorting = "ascending", # Sort value in descending order add = "segments", # Add segments from y = 0 to dots ggtheme = theme_pubr() # ggplot2 theme ) ``` -------------------------------- ### Create a violin plot with embedded box plots and p-values Source: https://github.com/kassambara/ggpubr/blob/master/README.md Generates a violin plot of 'len' by 'dose', filled by 'dose', with embedded box plots. Adds significance levels for pairwise comparisons and a global p-value. Requires the 'df' data frame and 'my_comparisons'. ```r # Violin plots with box plots inside # ::::::::::::::::::::::::::::::::::::::::::::::::::: # Change fill color by groups: dose # add boxplot with white fill color ggviolin(df, x = "dose", y = "len", fill = "dose", palette = c("#00AFBB", "#E7B800", "#FC4E07"), add = "boxplot", add.params = list(fill = "white"))+ stat_compare_means(comparisons = my_comparisons, label = "p.signif")+ # Add significance levels stat_compare_means(label.y = 50) # Add global the p-value ``` -------------------------------- ### ggbarplot: Simple Bar Plot with Data Labels Source: https://context7.com/kassambara/ggpubr/llms.txt Create a simple bar plot using ggbarplot. Set 'label = TRUE' to display data values on the bars and 'lab.pos = "out"' to place them outside. ```r library(ggpubr) # Simple bar plot with data labels df <- data.frame(dose = c("D0.5", "D1", "D2"), len = c(4.2, 10, 29.5)) ggbarplot(df, x = "dose", y = "len", fill = "dose", palette = "jco", label = TRUE, # Show values as labels lab.pos = "out") # Labels outside bars ``` -------------------------------- ### Export Plots to PDF Source: https://context7.com/kassambara/ggpubr/llms.txt Export single or arranged plots to PDF format using ggexport. Specify filename, width, and height for the output file. ```r library(ggpubr) data("ToothGrowth") df <- ToothGrowth df$dose <- as.factor(df$dose) # Create plots bxp <- ggboxplot(df, x = "dose", y = "len", color = "dose", palette = "jco") dp <- ggdotplot(df, x = "dose", y = "len", color = "dose", palette = "jco") dens <- ggdensity(df, x = "len", fill = "dose", palette = "jco") # Export single plot to PDF ggexport(bxp, filename = "boxplot.pdf") # Export arranged plots to PDF ggarrange(bxp, dp, dens, ncol = 2) %>% ggexport(filename = "combined_plots.pdf", width = 10, height = 8) ``` -------------------------------- ### Arrange Plots with Custom Widths Source: https://context7.com/kassambara/ggpubr/llms.txt Use ggarrange to arrange multiple plots, specifying custom widths for each plot to control their relative sizes. Align plots horizontally and vertically. ```r ggarrange(bxp, dens, ncol = 2, widths = c(2, 1), # First plot twice as wide align = "hv") # Align horizontally and vertically ``` -------------------------------- ### ggboxplot: Multiple Comparisons with Brackets Source: https://context7.com/kassambara/ggpubr/llms.txt Use stat_compare_means with the 'comparisons' argument for pairwise comparisons and 'label.y' to position brackets. A separate call to stat_compare_means can add a global p-value. ```r my_comparisons <- list(c("0.5", "1"), c("1", "2"), c("0.5", "2")) ggboxplot(df, x = "dose", y = "len", color = "dose", palette = "npg") + stat_compare_means(comparisons = my_comparisons, # Pairwise comparisons label.y = c(29, 35, 40)) + # Bracket positions stat_compare_means(label.y = 45) # Global p-value ``` -------------------------------- ### Apply Publication Theme with Panel Border Source: https://context7.com/kassambara/ggpubr/llms.txt Enhance the publication theme by adding a panel border using theme_pubr(border = TRUE). This clearly delineates the plot area. ```r p + theme_pubr(border = TRUE) ``` -------------------------------- ### Rotated Lollipop Chart with Labels and Customizations Source: https://github.com/kassambara/ggpubr/blob/master/README.md Creates a rotated lollipop chart with descending sort order, larger dot size, and displays mpg values as labels. Adjust label font properties using 'font.label'. ```r ggdotchart(dfm, x = "name", y = "mpg", color = "cyl", # Color by groups palette = c("#00AFBB", "#E7B800", "#FC4E07"), # Custom color palette sorting = "descending", # Sort value in descending order add = "segments", # Add segments from y = 0 to dots rotate = TRUE, # Rotate vertically group = "cyl", # Order by groups dot.size = 6, # Large dot size label = round(dfm$mpg), # Add mpg values as dot labels font.label = list(color = "white", size = 9, vjust = 0.5), # Adjust label parameters ggtheme = theme_pubr() # ggplot2 theme ) ``` -------------------------------- ### ggarrange: Arrangement with Publication Labels Source: https://context7.com/kassambara/ggpubr/llms.txt Add publication-style labels (A, B, C) to arranged plots using the 'labels' argument. Customize label appearance with 'font.label'. ```r library(ggpubr) data("ToothGrowth") df <- ToothGrowth df$dose <- as.factor(df$dose) # Create individual plots bxp <- ggboxplot(df, x = "dose", y = "len", color = "dose", palette = "jco") dp <- ggdotplot(df, x = "dose", y = "len", color = "dose", palette = "jco") dens <- ggdensity(df, x = "len", fill = "dose", palette = "jco") # With labels for publication ggarrange(bxp, dp, dens, labels = c("A", "B", "C"), # Panel labels ncol = 2, nrow = 2, font.label = list(size = 14, color = "black", face = "bold"), common.legend = TRUE, legend = "right") ``` -------------------------------- ### Align x-axis tick labels with 90-degree rotation Source: https://github.com/kassambara/ggpubr/blob/master/NEWS.md Ensures correct alignment of x-axis tick labels with ticks when text rotation is set to 90 degrees by internally setting `vjust = 0.5`. ```R ggboxplot(my_data, x = "dose", y = "len", color = "supp", palette = c("#00AFBB", "#E7B800"), order = c("D0", "D20", "D40"), ylab = "Len", xlab = "Dose") + theme(axis.text.x = element_text(angle = 90, vjust = 0.5)) ``` -------------------------------- ### ggline: Multi-group Line Plot Source: https://context7.com/kassambara/ggpubr/llms.txt Generate a multi-group line plot by mapping grouping variables to 'linetype', 'shape', and 'color' aesthetics. Use 'palette' to specify colors. ```r library(ggpubr) # Multi-group line plot df2 <- data.frame( supp = rep(c("VC", "OJ"), each = 3), dose = rep(c("D0.5", "D1", "D2"), 2), len = c(6.8, 15, 33, 4.2, 10, 29.5) ) ggline(df2, x = "dose", y = "len", linetype = "supp", shape = "supp", color = "supp", palette = c("#00AFBB", "#E7B800")) ``` -------------------------------- ### ggboxplot: Compare Against Reference Group Source: https://context7.com/kassambara/ggpubr/llms.txt Use stat_compare_means with 'method = "t.test"' and 'ref.group' to compare all groups against a specified reference group. 'anova' can be used for overall comparison. ```r ggboxplot(df, x = "dose", y = "len", color = "dose", palette = "npg") + stat_compare_means(method = "anova", label.y = 40) + stat_compare_means(aes(label = after_stat(p.signif)), method = "t.test", ref.group = "0.5") # Reference group ``` -------------------------------- ### Add crossout functionality to ggtexttable cells Source: https://github.com/kassambara/ggpubr/blob/master/NEWS.md Introduces `tab_cell_crossout()` to cross out specific cells within a `ggtexttable`. ```R tab_cell_crossout(text = "crossout", i = 1, j = 1) ``` -------------------------------- ### Perform t-test on ToothGrowth Data Source: https://github.com/kassambara/ggpubr/wiki/Adding-Adjusted-P-values-to-a-GGPlot Performs independent samples t-tests on the ToothGrowth dataset, grouped by 'supp'. It calculates the t-test for 'len' across different 'dose' levels. ```r # Statistical tests stat.test <- df %>% group_by(supp) %>% t_test(len ~ dose) stat.test ``` -------------------------------- ### Create Box Plot with P-values Source: https://github.com/kassambara/ggpubr/wiki/Adding-Adjusted-P-values-to-a-GGPlot Generates a faceted box plot of 'len' by 'dose', separated by 'supp', and adds adjusted p-values from a statistical test. Requires the 'stat.test' object with y-positions. ```r # Box plots with p-values stat.test <- stat.test %>% add_y_position() bxp <- ggboxplot(df, x = "dose", y = "len", facet.by = "supp") bxp + stat_pvalue_manual(stat.test, label = "p.adj", tip.length = 0.01) ``` -------------------------------- ### Facet Plots with Custom Panel Labels Source: https://context7.com/kassambara/ggpubr/llms.txt Customize the labels for faceted plots using the panel.labs argument. This allows for more descriptive or user-friendly panel titles. Set short.panel.labs to FALSE for full labels. ```r ggboxplot(ToothGrowth, x = "supp", y = "len", color = "supp", palette = "npg", facet.by = "dose", panel.labs = list(dose = c("Low", "Medium", "High")), short.panel.labs = FALSE) ``` -------------------------------- ### Facet Plots by Two Variables Source: https://context7.com/kassambara/ggpubr/llms.txt Generate faceted plots based on two variables by providing a vector of variable names to the facet.by argument. This creates a grid of panels. ```r data("mtcars") mtcars$cyl <- as.factor(mtcars$cyl) mtcars$gear <- as.factor(mtcars$gear) ggboxplot(mtcars, x = "cyl", y = "mpg", fill = "cyl", palette = "jco", facet.by = c("gear"), add = "jitter") ``` -------------------------------- ### ggboxplot: P-value Formatting Styles Source: https://context7.com/kassambara/ggpubr/llms.txt Customize p-value display using 'p.format.style' (e.g., 'apa') and 'p.digits' for decimal places. Use 'label = "p.format.signif"' to show p-values with significance stars. ```r ggboxplot(df, x = "dose", y = "len", color = "dose") + stat_compare_means(comparisons = my_comparisons, p.format.style = "apa", # APA style p.digits = 3, # 3 decimal places label = "p.format.signif") # Show p-value with stars ``` -------------------------------- ### Add vertical lines to ggtexttable columns Source: https://github.com/kassambara/ggpubr/blob/master/NEWS.md Use `tab_add_vline()` to add vertical lines or separators to the right or left of specified columns in a `ggtexttable`. ```R tab_add_vline(where = "right", col = 1) ``` -------------------------------- ### Facet Plots by Single Variable Source: https://context7.com/kassambara/ggpubr/llms.txt Create faceted plots by specifying a single variable in the facet.by argument of ggboxplot. This generates panels for each level of the specified variable. ```r library(ggpubr) data("ToothGrowth") # Facet by single variable ggboxplot(ToothGrowth, x = "supp", y = "len", color = "supp", palette = "npg", add = "jitter", facet.by = "dose") # Facet by dose ``` -------------------------------- ### Export Plots to TIFF for Publication Source: https://context7.com/kassambara/ggpubr/llms.txt Export plots to TIFF format using ggexport, suitable for publications. Specify dimensions and resolution for print quality. ```r ggexport(bxp, filename = "figure.tiff", width = 2400, height = 2400, res = 300) ``` -------------------------------- ### Use ColorBrewer Palettes Source: https://context7.com/kassambara/ggpubr/llms.txt Apply a ColorBrewer palette, such as 'RdBu' (Red-Blue diverging), to a ggboxplot. This is useful for creating plots with specific color gradients. ```r ggboxplot(ToothGrowth, x = "dose", y = "len", fill = "dose", palette = "RdBu") # Red-Blue diverging ``` -------------------------------- ### Update ggdensity and gghistogram for ggplot2 v3.4.0 Source: https://github.com/kassambara/ggpubr/blob/master/NEWS.md Replaces dot-dot notation (`..density..`, `..count..`) with `after_stat(density)` and `after_stat(count)` in `ggdensity()` and `gghistogram()` for compatibility with ggplot2 3.4.0. ```R ggdensity(data, x = "x", fill = "Stage", palette = c("#00AFBB", "#E7B800")) + scale_x_continuous(breaks = seq(0, 10, by = 2)) ``` ```R gghistogram(data, x = "x", fill = "Stage", palette = c("#00AFBB", "#E7B800")) ``` -------------------------------- ### Create Ordered Bar Plot Source: https://github.com/kassambara/ggpubr/blob/master/README.md Generates an ordered bar plot using ggbarplot, with bars filled by the 'cyl' grouping variable. Bars are sorted in descending order globally, not by group. ```r ggbarplot(dfm, x = "name", y = "mpg", fill = "cyl", # change fill color by cyl color = "white", # Set bar border colors to white palette = "jco", # jco journal color palett. see ?ggpar sort.val = "desc", # Sort the value in dscending order sort.by.groups = FALSE, # Don't sort inside each group x.text.angle = 90 # Rotate vertically x axis texts ) ``` -------------------------------- ### ggline: Line Plot with Jitter Points Source: https://context7.com/kassambara/ggpubr/llms.txt Combine error bars with jittered points on a line plot using 'add = c("mean_se", "jitter")'. Use 'error.plot = "pointrange"' for point range error bars and 'position = position_dodge(0.2)' to prevent overlap. ```r library(ggpubr) # Line plot with jitter points ggline(ToothGrowth, x = "dose", y = "len", color = "supp", add = c("mean_se", "jitter"), # Error bars + jitter palette = c("#00AFBB", "#E7B800"), error.plot = "pointrange", # Point range error bars position = position_dodge(0.2)) # Dodge overlapping points ``` -------------------------------- ### Calculate MPG Z-score and Group Source: https://github.com/kassambara/ggpubr/blob/master/README.md Calculates the z-score for the 'mpg' variable and creates a grouping factor 'mpg_grp' based on whether the z-score is positive or negative. Inspects the resulting data frame. ```r # Calculate the z-score of the mpg data dfm$mpg_z <- (dfm$mpg -mean(dfm$mpg))/sd(dfm$mpg) dfm$mpg_grp <- factor(ifelse(dfm$mpg_z < 0, "low", "high"), levels = c("low", "high")) # Inspect the data head(dfm[, c("name", "wt", "mpg", "mpg_z", "mpg_grp", "cyl")]) ``` -------------------------------- ### Use Custom Color Vectors Source: https://context7.com/kassambara/ggpubr/llms.txt Define and apply a custom vector of colors to a ggboxplot. This allows for precise control over plot aesthetics when predefined palettes are insufficient. ```r ggboxplot(ToothGrowth, x = "dose", y = "len", fill = "dose", palette = c("#E64B35", "#4DBBD5", "#00A087")) ``` -------------------------------- ### Use Nature Publishing Group Color Palette Source: https://context7.com/kassambara/ggpubr/llms.txt Apply the 'npg' color palette from ggsci, mimicking Nature Publishing Group's color scheme, to a ggboxplot. This ensures consistent and professional aesthetics. ```r library(ggpubr) data("ToothGrowth") # Using journal palettes ggboxplot(ToothGrowth, x = "dose", y = "len", fill = "dose", palette = "npg") # Nature palette ``` -------------------------------- ### ggarrange: Basic Arrangement Source: https://context7.com/kassambara/ggpubr/llms.txt Combine multiple ggplot objects into a single figure using ggarrange. Specify the number of columns and rows for the layout. ```r library(ggpubr) data("ToothGrowth") df <- ToothGrowth df$dose <- as.factor(df$dose) # Create individual plots bxp <- ggboxplot(df, x = "dose", y = "len", color = "dose", palette = "jco") dp <- ggdotplot(df, x = "dose", y = "len", color = "dose", palette = "jco") dens <- ggdensity(df, x = "len", fill = "dose", palette = "jco") # Basic arrangement ggarrange(bxp, dp, dens, ncol = 2, nrow = 2) ``` -------------------------------- ### Add horizontal lines to ggtexttable rows Source: https://github.com/kassambara/ggpubr/blob/master/NEWS.md Use `tab_add_hline()` to add horizontal lines or separators at the top or bottom of specified rows in a `ggtexttable`. ```R tab_add_hline(where = "bottom", row = 1) ``` -------------------------------- ### ggarrange: Arrangement with Common Legend Source: https://context7.com/kassambara/ggpubr/llms.txt Share a common legend among plots in an arrangement by setting 'common.legend = TRUE'. Specify the legend position using the 'legend' argument. ```r library(ggpubr) data("ToothGrowth") df <- ToothGrowth df$dose <- as.factor(df$dose) # Create individual plots bxp <- ggboxplot(df, x = "dose", y = "len", color = "dose", palette = "jco") dp <- ggdotplot(df, x = "dose", y = "len", color = "dose", palette = "jco") # With common legend ggarrange(bxp, dp, common.legend = TRUE, # Share legend legend = "bottom") # Legend position ``` -------------------------------- ### ggline: Line Plot with Mean and Error Bars Source: https://context7.com/kassambara/ggpubr/llms.txt Add mean and standard error to a line plot using 'add = "mean_se"'. This is useful for visualizing summary statistics from raw data. ```r library(ggpubr) # Line plot with mean and error bars from raw data data("ToothGrowth") ggline(ToothGrowth, x = "dose", y = "len", color = "supp", add = "mean_se", # Mean + standard error palette = c("#00AFBB", "#E7B800")) ``` -------------------------------- ### Format P-values for Display Source: https://github.com/kassambara/ggpubr/wiki/Adding-Adjusted-P-values-to-a-GGPlot Formats the adjusted p-values in the 'stat.test' object for cleaner display on plots. It removes leading zeros and sets accuracy. ```r # Format-p-values stat.test <- stat.test %>% p_format(p.adj, leading.zero = FALSE, accuracy = 0.0001) bxp + stat_pvalue_manual(stat.test, label = "p.adj", tip.length = 0.01) ``` -------------------------------- ### ggboxplot with single numeric vector Source: https://github.com/kassambara/ggpubr/blob/master/NEWS.md Demonstrates the usage of ggboxplot with a single numeric vector. This functionality was introduced in ggpubr version 0.1.1. ```r ggboxplot(iris$Sepal.Length) ``` -------------------------------- ### Create Ordered Bar Plot Sorted by Groups Source: https://github.com/kassambara/ggpubr/blob/master/README.md Generates an ordered bar plot using ggbarplot, with bars filled by the 'cyl' grouping variable. Bars are sorted in ascending order within each group. ```r ggbarplot(dfm, x = "name", y = "mpg", fill = "cyl", # change fill color by cyl color = "white", # Set bar border colors to white palette = "jco", # jco journal color palett. see ?ggpar sort.val = "asc", # Sort the value in dscending order sort.by.groups = TRUE, # Sort inside each group x.text.angle = 90 # Rotate vertically x axis texts ) ```