Maintainers
Pricing
Enterprise
More
More
Documentation
Try Live
Rankings
Install
Blog
Docs7
Ask
New
Add Docs
ggpubr
https://r-packages.io/packages/ggpubr
Admin
ggpubr is an R package that provides a simple way to create publication-ready ggplot2
...
Tokens:
100,507
Snippets:
802
Trust Score:
6.5
Update:
3 months ago
Context
Chat
Benchmark
Latest
Show doc for...
Code
Info
Show Results
Tokens:
Raw
Copy
Link
Tokens:
Raw
Copy
Link
### Install and use png package for background image Source: https://r-packages.io/packages/ggpubr/background_image Demonstrates how to install the png package, read a PNG image file using system.file, and then use it as a background for a ggplot2 plot with the background_image function. Requires the ggpubr and ggplot2 packages. ```R install.packages("png") # Import the image img.file <- system.file(file.path("images", "background-image.png"), package = "ggpubr") img <- png::readPNG(img.file) # Plot with background image ggplot(iris, aes(Species, Sepal.Length))+ background_image(img)+ geom_boxplot(aes(fill = Species), color = "white")+ fill_palette("jco") ``` -------------------------------- ### Set Ticks by Step and Starting Point Source: https://r-packages.io/packages/ggpubr/get_breaks Shows how to set axis ticks using a specific step and starting point, along with axis limits, for a ggplot. ```r # Set ticks according to a specific step, starting from 0 p + scale_x_continuous( breaks = get_breaks(by = 1.5, from = 0), limits = c(0, 6) ) + scale_y_continuous( breaks = get_breaks(by = 10, from = 0), limits = c(0, 40) ) ``` -------------------------------- ### Apply Blank Table Theme Source: https://r-packages.io/packages/ggpubr/ggtexttable Creates a table with a blank theme, useful for starting with a clean slate or when only borders are needed. ```R df <- head(iris) # Blank theme ggtexttable(df, rows = NULL, theme = ttheme("blank")) ``` -------------------------------- ### Data Preparation for Boxplot Example Source: https://r-packages.io/packages/ggpubr/ggadjust_pvalue Prepares the ToothGrowth dataset by converting the 'dose' column to a factor and adding a random grouping variable. This data is used for subsequent boxplot examples. ```R # Data preparation #::::::::::::::::::::::::::::::::::::::: df <- ToothGrowth df$dose <- as.factor(df$dose) # Add a random grouping variable df$group <- factor(rep(c("grp1", "grp2"), 30)) head(df, 3) ``` -------------------------------- ### Add Mean and Standard Deviation to Violin Plot Source: https://r-packages.io/packages/ggpubr/add_summary This example demonstrates how to add mean and standard deviation summary statistics to a basic violin plot created using ggviolin. Ensure the 'ggpubr' package is installed and loaded. ```R # Basic violin plot p <- ggviolin(ToothGrowth, x = "dose", y = "len", add = "none") p # Add mean_sd add_summary(p, "mean_sd") ``` -------------------------------- ### Data Preparation for ggsummarystats Source: https://r-packages.io/packages/ggpubr/ggsummarystats Prepares the ToothGrowth dataset by converting dose to a factor and adding a random QC column. This data is used in subsequent examples. ```R # Data preparation #:::::::::::::::::::::::::::::::::::::::::::::::: data("ToothGrowth") df <- ToothGrowth df$dose <- as.factor(df$dose) # Add random QC column set.seed(123) qc <- rep(c("pass", "fail"), 30) df$qc <- as.factor(sample(qc, 60)) # Inspect the data head(df) ``` -------------------------------- ### ggpubr yscale log2 example Source: https://r-packages.io/packages/ggpubr/axis_scale Demonstrates how to apply a log2 scale to the y-axis of a scatter plot using the yscale function with label formatting enabled. ```r # Basic scatter plots data(cars) p <- ggscatter(cars, x = "speed", y = "dist") p # Set log scale p + yscale("log2", .format = TRUE) ``` -------------------------------- ### Data Preparation for Friedman Test Source: https://r-packages.io/packages/ggpubr/stat_friedman_test Prepares the ToothGrowth dataset by converting 'dose' and 'id' to factors, and adding a random grouping variable 'group'. This setup is necessary for demonstrating grouped statistical tests. ```R df <- ToothGrowth df$dose <- as.factor(df$dose) df$id <- as.factor(c(rep(1:10, 3), rep(11:20, 3))) # Add a random grouping variable set.seed(123) df$group <- sample(factor(rep(c("grp1", "grp2", "grp3"), 20))) df$len <- ifelse(df$group == "grp2", df$len+2, df$len) df$len <- ifelse(df$group == "grp3", df$len+7, df$len) head(df, 3) ``` -------------------------------- ### Export ggplot to PNG Source: https://r-packages.io/packages/ggpubr/ggexport Example demonstrating how to export a grid of plots to a PNG file using ggexport. Requires ggpubr and magrittr packages. ```r require("magrittr") # Load data data("ToothGrowth") df <- ToothGrowth df$dose <- as.factor(df$dose) # Box plot bxp <- ggboxplot(df, x = "dose", y = "len", color = "dose", palette = "jco") # Dot plot dp <- ggdotplot(df, x = "dose", y = "len", color = "dose", palette = "jco") # Density plot dens <- ggdensity(df, x = "len", fill = "dose", palette = "jco") # Export to png ggarrange(bxp, dp, dens, ncol = 2) %>% ggexport(filename = "test.png") ``` -------------------------------- ### Export ggplot to PDF Source: https://r-packages.io/packages/ggpubr/ggexport Example demonstrating how to export a grid of plots to a PDF file using ggexport. Requires ggpubr and magrittr packages. ```r require("magrittr") # Load data data("ToothGrowth") df <- ToothGrowth df$dose <- as.factor(df$dose) # Box plot bxp <- ggboxplot(df, x = "dose", y = "len", color = "dose", palette = "jco") # Dot plot dp <- ggdotplot(df, x = "dose", y = "len", color = "dose", palette = "jco") # Density plot dens <- ggdensity(df, x = "len", fill = "dose", palette = "jco") # Export to pdf ggarrange(bxp, dp, dens, ncol = 2) %>% ggexport(filename = "test.pdf") ``` -------------------------------- ### Basic Plotting Example Source: https://r-packages.io/packages/ggpubr/theme_pubr A basic ggplot2 scatter plot using mtcars dataset, serving as a base for theme application. ```r p <- ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point(aes(color = gear)) ``` -------------------------------- ### Generate Breaks for a Variable Source: https://r-packages.io/packages/ggpubr/get_breaks Example of generating a specified number of breaks for a numeric variable. ```r # Generate 5 breaks for a variable x get_breaks(n = 5)(x = 1:100) ``` -------------------------------- ### Customizing Facet Labels and Appearance Source: https://r-packages.io/packages/ggpubr/facet Shows how to customize facet labels and panel backgrounds using the facet function. This example disables short panel labels and sets a custom background fill and color for the panels. ```R facet(p + theme_bw(), facet.by = "supp", short.panel.labs = FALSE, # Allow long labels in panels panel.labs.background = list(fill = "steelblue", color = "steelblue") ) ``` -------------------------------- ### Pairwise mean comparison example Source: https://r-packages.io/packages/ggpubr/compare_means Automatically performs pairwise comparisons when the grouping variable has more than two levels. Uses the ToothGrowth dataset. ```r # pairwise comparisons #:::::::::::::::::::::::::::::::::::::::: # As dose contains more thant two levels ==> # pairwise test is automatically performed. compare_means(len ~ dose, df) ``` -------------------------------- ### Data Preparation for ANOVA Test Source: https://r-packages.io/packages/ggpubr/stat_welch_anova_test Prepares the ToothGrowth dataset by converting 'dose' to a factor, adding a random grouping variable, and adjusting 'len' based on the group. This setup is used for demonstrating ANOVA tests. ```R df <- ToothGrowth df$dose <- as.factor(df$dose) set.seed(123) df$group <- sample(factor(rep(c("grp1", "grp2", "grp3"), 20))) df$len <- ifelse(df$group == "grp2", df$len+2, df$len) df$len <- ifelse(df$group == "grp3", df$len+7, df$len) head(df, 3) ``` -------------------------------- ### Calculate Descriptive Statistics by Groups Source: https://r-packages.io/packages/ggpubr/desc_statby This example demonstrates how to use desc_statby to compute descriptive statistics for the 'len' variable in the ToothGrowth dataset, grouped by 'dose' and 'supp'. The head of the resulting data frame is displayed. ```R # Load data data("ToothGrowth") # Descriptive statistics res <- desc_statby(ToothGrowth, measure.var = "len", grps = c("dose", "supp")) head(res[, 1:10]) ``` -------------------------------- ### Facet by Species Source: https://r-packages.io/packages/ggpubr/stat_overlay_normal_density This example demonstrates how to create faceted density plots for sepal length in the iris dataset, with a red dashed normal density curve overlaid on each facet. The `facet.by = "Species"` argument creates separate plots for each species. ```r # Facet ggdensity(iris, "Sepal.Length", facet.by = "Species") + stat_overlay_normal_density(color = "red", linetype = "dashed") ``` -------------------------------- ### One-sample t-test example Source: https://r-packages.io/packages/ggpubr/compare_means Performs a one-sample t-test to compare the mean of a variable to a specified value (mu). Requires the ToothGrowth dataset. ```r # Load data #:::::::::::::::::::::::::::::::::::::: data("ToothGrowth") df <- ToothGrowth # One-sample test #::::::::::::::::::::::::::::::::::::::::: compare_means(len ~ 1, df, mu = 0) ``` -------------------------------- ### Overlay Normal Density Plot Source: https://r-packages.io/packages/ggpubr/stat_overlay_normal_density This example demonstrates how to overlay a normal density plot with a dashed red line to the density distribution of 'mpg' from the mtcars dataset. It also shows how to set x-axis limits. ```r # Simple density plot data("mtcars") ggdensity(mtcars, x = "mpg", fill = "red") + scale_x_continuous(limits = c(-1, 50)) + stat_overlay_normal_density(color = "red", linetype = "dashed") ``` -------------------------------- ### Color by Groups Source: https://r-packages.io/packages/ggpubr/stat_overlay_normal_density This example shows how to overlay normal density plots for different species in the iris dataset, coloring each density curve according to the species. It uses `aes(color = Species)` to map the color aesthetic to the 'Species' variable. ```r # Color by groups data(iris) ggdensity(iris, "Sepal.Length", color = "Species") + stat_overlay_normal_density(aes(color = Species), linetype = "dashed") ``` -------------------------------- ### Data Preparation for Kruskal-Wallis Test Source: https://r-packages.io/packages/ggpubr/stat_kruskal_test Prepares the ToothGrowth dataset by converting 'dose' to a factor and adding a random grouping variable. This setup is necessary for demonstrating the Kruskal-Wallis test on grouped data. ```R # Data preparation #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% # Transform `dose` into factor variable df <- ToothGrowth df$dose <- as.factor(df$dose) # Add a random grouping variable set.seed(123) df$group <- sample(factor(rep(c("grp1", "grp2", "grp3"), 20))) df$len <- ifelse(df$group == "grp2", df$len+2, df$len) df$len <- ifelse(df$group == "grp3", df$len+7, df$len) head(df, 3) ``` -------------------------------- ### Add Median as Points to Density Plot Source: https://r-packages.io/packages/ggpubr/stat_central_tendency Shows how to display the median of 'Sepal.Length' as points on a density plot using the iris dataset. This example customizes the geom to 'point' and adjusts its size. ```r # Use geom = "point" for central tendency data(iris) ggdensity(iris, "Sepal.Length", color = "Species") + stat_central_tendency( aes(color = Species), type = "median", geom = "point", size = 4 ) ``` -------------------------------- ### Style Multiple Cells in ggtexttable Source: https://r-packages.io/packages/ggpubr/ggtexttable Applies font and background styles to a range of cells. This example styles column 3 from row 2 to the last row with italic font and white color, and a dark blue background. ```R tab <- ggtexttable(df, rows = NULL, theme = ttheme("classic")) tab %>% table_cell_bg(row = 2:tab_nrow(tab), column = 3, fill = "darkblue") %>% table_cell_font(row = 2:tab_nrow(tab), column = 3, face = "italic", color = "white") ``` -------------------------------- ### Simple Aes Creation with create_aes Source: https://r-packages.io/packages/ggpubr/create_aes Demonstrates the basic usage of create_aes to map 'Sepal.Length' to the x-axis and 'Petal.Length' to the y-axis. ```r # Simple aes creation create_aes(list(x = "Sepal.Length", y = "Petal.Length" )) ``` -------------------------------- ### Create a Scatter Plot with Transparent Theme Source: https://r-packages.io/packages/ggpubr/theme_transparent Demonstrates how to create a scatter plot using ggscatter and then apply the theme_transparent to it. ```r # Create a scatter plot sp <- ggscatter(iris, x = "Sepal.Length", y = "Sepal.Width", color = "Species", palette = "jco", size = 3, alpha = 0.6) sp # Transparent theme sp + theme_transparent() ``` -------------------------------- ### Create ggtexttable with Minimal Theme Source: https://r-packages.io/packages/ggpubr/ggtexttable Use the 'minimal' theme for a clean and simple table appearance. The 'rows = NULL' argument indicates that default row names should not be displayed. ```R ggtexttable(df, rows = NULL, theme = ttheme("minimal")) ``` -------------------------------- ### Visualize Summary Table Source: https://r-packages.io/packages/ggpubr/ggsummarystats Creates a summary table visualization using ggsummarytable, displaying 'n', 'median', and 'iqr' statistics against 'dose'. Uses a black and white theme. ```R # Visualize summary table ggsummarytable( summary.stats, x = "dose", y = c("n", "median", "iqr"), ggtheme = theme_bw() ) ``` -------------------------------- ### Get Number of Rows with tab_nrow Source: https://r-packages.io/packages/ggpubr/ggtexttable Returns the number of rows in a ggtexttable object. ```r tab_nrow(tab) ``` -------------------------------- ### Get Number of Columns with tab_ncol Source: https://r-packages.io/packages/ggpubr/ggtexttable Returns the number of columns in a ggtexttable object. ```r tab_ncol(tab) ``` -------------------------------- ### Parse Expression for Aes Mapping Source: https://r-packages.io/packages/ggpubr/create_aes Shows how to use create_aes with `parse = TRUE` to map log-transformed variables to the x and y axes. ```r # Parse an expression x <- "log2(Sepal.Length)" y <- "log2(Petal.Length)" create_aes(list(x = x, y = y ), parse = TRUE) ``` -------------------------------- ### Create ggtexttable with mBlue Theme Source: https://r-packages.io/packages/ggpubr/ggtexttable Applies the 'mBlue' theme for a blue-toned table. Ensure the 'df' object is properly defined before use. ```R ggtexttable(df, rows = NULL, theme = ttheme("mBlue")) ``` -------------------------------- ### Generate Breaks with a Specific Step Source: https://r-packages.io/packages/ggpubr/get_breaks Example of generating breaks with a defined step between ticks for a numeric variable. ```r # Generate breaks using an increasing step get_breaks(by = 10)(x = 1:100) ``` -------------------------------- ### Specify Multiple Brackets Manually Source: https://r-packages.io/packages/ggpubr/geom_bracket Demonstrates how to specify multiple brackets by providing vectors for xmin, xmax, y.position, and label. ```R # Specify multiple brackets manually ggboxplot(df, x = "dose", y = "len") + geom_bracket( xmin = c("0.5", "1"), xmax = c("1", "2"), y.position = c(30, 35), label = c("***", "**"), tip.length = 0.01 ) ``` -------------------------------- ### Apply Light Table Theme Source: https://r-packages.io/packages/ggpubr/ggtexttable Generates a table using the 'light' theme, providing a clean and minimalist appearance. ```R df <- head(iris) # light theme ggtexttable(df, rows = NULL, theme = ttheme("light")) ``` -------------------------------- ### Change Comparison Method (Independent Groups) Source: https://r-packages.io/packages/ggpubr/stat_compare_means Modifies the statistical test used for comparison in a ggboxplot. This example uses the t.test method. ```R p + stat_compare_means(method = "t.test") ``` -------------------------------- ### Grouped mean comparison example Source: https://r-packages.io/packages/ggpubr/compare_means Compares means of a variable between groups, further stratified by another grouping variable. Uses the ToothGrowth dataset. ```r # Compare supp levels after grouping the data by "dose" #:::::::::::::::::::::::::::::::::::::::: compare_means(len ~ supp, df, group.by = "dose") ``` -------------------------------- ### Create Sample Data for ECDF Plot Source: https://r-packages.io/packages/ggpubr/ggecdf Generates a sample data frame named 'wdata' with 'sex' and 'weight' columns, suitable for demonstrating ECDF plotting with ggpubr. ```r 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) ``` -------------------------------- ### Create Basic Density Plot with Mean Line and Rug Source: https://r-packages.io/packages/ggpubr/ggdensity Generates a basic density plot for the 'weight' variable, adding a mean line and a marginal rug plot. Requires the ggdensity function and sample data. ```R 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) # Basic density plot # Add mean line and marginal rug ggdensity(wdata, x = "weight", fill = "lightgray", add = "mean", rug = TRUE) ``` -------------------------------- ### Balloon Plot for Stretched Table Source: https://r-packages.io/packages/ggpubr/ggballoonplot Visualizes a stretched contingency table where size and fill are mapped to a 'Value' column. Guides for size can be hidden. ```R # Streched contingency table #::::::::::::::::::::::::::::::::::::::::::::::::::::::::: # Create an Example Data Frame Containing Car x Color data carnames <- c("bmw","renault","mercedes","seat") carcolors <- c("red","white","silver","green") datavals <- round(rnorm(16, mean=100, sd=60),1) car_data <- data.frame(Car = rep(carnames,4), Color = rep(carcolors, c(4,4,4,4) ), Value=datavals ) car_data ggballoonplot(car_data, x = "Car", y = "Color", size = "Value", fill = "Value") + scale_fill_gradientn(colors = my_cols) + guides(size = FALSE) ``` -------------------------------- ### Create and Draw a Customized Text Grob Source: https://r-packages.io/packages/ggpubr/text_grob Demonstrates how to create a multi-line text grob with specified formatting (italic, steelblue color) and then draw it using as_ggplot. This is useful for adding formatted text annotations to plots. ```R text <- paste("iris data set gives the measurements in cm", "of the variables sepal length and width", "and petal length and width, respectively,", "for 50 flowers from each of 3 species of iris.", "The species are Iris setosa, versicolor, and virginica.", sep = "\n") # Create a text grob tgrob <- text_grob(text, face = "italic", color = "steelblue") # Draw the text as_ggplot(tgrob) ``` -------------------------------- ### ANOVA and Kruskal-Wallis test examples Source: https://r-packages.io/packages/ggpubr/compare_means Performs one-way ANOVA or Kruskal-Wallis tests for comparing means across multiple groups. Uses the ToothGrowth dataset. ```r # Anova and kruskal.test #:::::::::::::::::::::::::::::::::::::::: compare_means(len ~ dose, df, method = "anova") compare_means(len ~ dose, df, method = "kruskal.test") ``` -------------------------------- ### Two-samples unpaired t-test example Source: https://r-packages.io/packages/ggpubr/compare_means Performs an unpaired t-test to compare the means of a variable between two groups defined by a factor. Uses the ToothGrowth dataset. ```r # Two-samples unpaired test #::::::::::::::::::::::::::::::::::::::::: compare_means(len ~ supp, df) ``` -------------------------------- ### Basic ggstripchart with Mean and SE Source: https://r-packages.io/packages/ggpubr/ggstripchart Generates a basic strip plot showing the length of tooth growth for different doses, with mean and standard error added. The shape of the points is varied by dose. ```R data("ToothGrowth") df <- ToothGrowth ggstripchart(df, x = "dose", y = "len", shape = "dose", size = 3, add = "mean_se") ``` -------------------------------- ### Basic Faceting with ggpubr Source: https://r-packages.io/packages/ggpubr/facet Demonstrates the basic usage of the facet function to create a multi-panel plot faceted by a single grouping variable. ```R p <- ggboxplot(ToothGrowth, x = "dose", y = "len", color = "supp") print(p) facet(p, facet.by = "supp") ``` -------------------------------- ### Scatter Plot with Polygon Convex Hull Source: https://r-packages.io/packages/ggpubr/stat_chull Creates a scatter plot similar to the previous example but fills the convex hulls with color and transparency, using a polygon geometry. ```R ggscatter(df, x = "wt", y = "mpg", color = "cyl")+ stat_chull(aes(color = cyl, fill = cyl), alpha = 0.1, geom = "polygon") ``` -------------------------------- ### Annotating an Arranged ggplot Figure Source: https://r-packages.io/packages/ggpubr/annotate_figure Example demonstrating how to use annotate_figure to add various text annotations and a figure label to an arranged ggplot. Requires ggpubr and ggplot2. ```r data("ToothGrowth") df <- ToothGrowth df$dose <- as.factor(df$dose) # Create some plots # :::::::::::::::::::::::::::::::::::::::::::::::::: # Box plot bxp <- ggboxplot(df, x = "dose", y = "len", color = "dose", palette = "jco") # Dot plot dp <- ggdotplot(df, x = "dose", y = "len", color = "dose", palette = "jco") # Density plot dens <- ggdensity(df, x = "len", fill = "dose", palette = "jco") # Arrange and annotate # :::::::::::::::::::::::::::::::::::::::::::::::::: figure <- ggarrange(bxp, dp, dens, ncol = 2, nrow = 2) annotate_figure(figure, top = text_grob("Visualizing Tooth Growth", color = "red", face = "bold", size = 14), bottom = text_grob("Data source: \n ToothGrowth data set", color = "blue", hjust = 1, x = 1, face = "italic", size = 10), left = text_grob("Figure arranged using ggpubr", color = "green", rot = 90), right = text_grob(bquote("Superscript: ("*kg~NH[3]~ha^-1~yr^-1*")"), rot = 90), fig.lab = "Figure 1", fig.lab.face = "bold" ) ``` -------------------------------- ### Display allowed global options Source: https://r-packages.io/packages/ggpubr/ggpubr_options Call the ggpubr_options() function without any arguments to display all available global options. ```r ggpubr_options() ``` -------------------------------- ### Two-samples paired t-test example Source: https://r-packages.io/packages/ggpubr/compare_means Performs a paired t-test to compare the means of a variable between two related groups. Requires the 'paired = TRUE' argument. Uses the ToothGrowth dataset. ```r # Two-samples paired test #::::::::::::::::::::::::::::::::::::::::: compare_means(len ~ supp, df, paired = TRUE) ``` -------------------------------- ### Basic ECDF Plot Source: https://r-packages.io/packages/ggpubr/ggecdf Generates a basic Empirical Cumulative Density Function (ECDF) plot using the 'weight' variable from the 'wdata' data frame. This serves as a starting point for further customization. ```r ggecdf(wdata, x = "weight") ``` -------------------------------- ### Data Preparation for ANOVA Tests Source: https://r-packages.io/packages/ggpubr/stat_anova_test Prepares the ToothGrowth dataset by converting 'dose' to a factor, adding individual IDs, and creating a random grouping variable. It also modifies the 'len' variable based on the group for demonstration purposes. ```R # Data preparation #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% # Transform `dose` into factor variable df <- ToothGrowth df$dose <- as.factor(df$dose) # Add individuals id df$id <- rep(1:10, 6) # Add a random grouping variable set.seed(123) df$group <- sample(factor(rep(c("grp1", "grp2", "grp3"), 20))) df$len <- ifelse(df$group == "grp2", df$len+2, df$len) df$len <- ifelse(df$group == "grp3", df$len+7, df$len) head(df, 3) ``` -------------------------------- ### Transform arrangeGrob output to ggplot Source: https://r-packages.io/packages/ggpubr/as_ggplot Demonstrates how to use as_ggplot to convert a gtable object created by arrangeGrob into a ggplot object for further use. Requires the gridExtra package. ```r library(gridExtra) bxp <- ggboxplot(iris, x = "Species", y = "Sepal.Length") vp <- ggviolin(iris, x = "Species", y = "Sepal.Length", add = "mean_sd") gt <- arrangeGrob(bxp, vp, ncol = 2) as_ggplot(gt) ``` -------------------------------- ### get_breaks Source: https://r-packages.io/packages/ggpubr/get_breaks Creates breaks for numeric axes to be used in scale_x_continuous() and scale_y_continuous(). It allows users to specify the number of breaks (n) or the step between breaks (by), and optionally define the starting (from) and ending (to) values for the breaks. ```APIDOC ## get_breaks ### Description Creates breaks for numeric axes to be used in the functions `scale_x_continuous()` and `scale_y_continuous()`. It allows control over the number of x and y ticks by specifying the option `n`, or by controlling the axis breaks by specifying a step between ticks using `by`. ### Function Signature ```r get_breaks(n = NULL, by = NULL, from = NULL, to = NULL) ``` ### Arguments * `n` (numeric): The desired number of breaks. * `by` (numeric): The step size between breaks. For example, if `by = 5`, a tick mark is shown on every 5 units. * `from` (numeric): The starting value for the breaks. Defaults to 0 for positive variables. * `to` (numeric): The end value for the breaks, typically corresponding to the maximum limit of the axis. ### Returns A break function that can be applied to ggplot scales. ### Examples ```r # Generate 5 breaks for a variable x get_breaks(n = 5)(x = 1:100) # Generate breaks using an increasing step get_breaks(by = 10)(x = 1:100) # Combine with ggplot scale_xx functions library(ggplot2) # Create a basic plot p <- ggscatter(mtcars, x = "wt", y = "mpg") p # Increase the number of ticks p + scale_x_continuous(breaks = get_breaks(n = 10)) + scale_y_continuous(breaks = get_breaks(n = 10)) # Set ticks according to a specific step, starting from 0 p + scale_x_continuous( breaks = get_breaks(by = 1.5, from = 0), limits = c(0, 6) ) + scale_y_continuous( breaks = get_breaks(by = 10, from = 0), limits = c(0, 40) ) ``` ``` -------------------------------- ### Apply Classic Table Theme Source: https://r-packages.io/packages/ggpubr/ggtexttable Renders a table with the 'classic' theme, which typically includes borders and standard formatting. ```R df <- head(iris) # classic theme ggtexttable(df, rows = NULL, theme = ttheme("classic")) ``` -------------------------------- ### Custom Text Justification in Table Cells Source: https://r-packages.io/packages/ggpubr/ggtexttable Applies custom text justification to table cells using tbody_style. This example demonstrates left justification for the first column and right justification for the rest. ```R df <- head(iris) table_theme <- ttheme( tbody.style = tbody_style( hjust = as.vector(matrix(c(0, 1, 1, 1, 1), ncol = 5, nrow = nrow(df), byrow = TRUE)), x = as.vector(matrix(c(.1, .9, .9,.9, .9), ncol = 5, nrow = nrow(df), byrow = TRUE)) ) ) ggtexttable(df, rows = NULL, theme = table_theme) ``` -------------------------------- ### ggstripchart with Multiple Groups (Shape and Color) Source: https://r-packages.io/packages/ggpubr/ggstripchart Generates a strip plot visualizing tooth growth, with both point shape and color differentiated by the 'supp' group. A specific color palette is applied. ```R ggstripchart(df, "dose", "len", shape = "supp", color = "supp", palette = c("#00AFBB", "#E7B800")) ``` -------------------------------- ### Compute Statistical Tests and Add P-values Source: https://r-packages.io/packages/ggpubr/geom_bracket Shows how to compute statistical tests (e.g., t-test) using compare_means and then add the significance levels as labels to the brackets. ```R # Compute statistical tests and add p-values stat.test <- compare_means(len ~ dose, ToothGrowth, method = "t.test") ggboxplot(df, x = "dose", y = "len") + geom_bracket( aes(xmin = group1, xmax = group2, label = signif(p, 2)), data = stat.test, y.position = 35 ) ``` -------------------------------- ### Add Median by Group to Density Plot Source: https://r-packages.io/packages/ggpubr/stat_central_tendency Illustrates adding a dashed line for the median of 'Sepal.Length', colored by 'Species', to a density plot of the iris dataset. This example shows how to map aesthetics to grouping variables. ```r # Color by groups data(iris) ggdensity(iris, "Sepal.Length", color = "Species") + stat_central_tendency(aes(color = Species), type = "median", linetype = 2) ``` -------------------------------- ### Customize Point Shape Display with Theme Source: https://r-packages.io/packages/ggpubr/show_point_shapes Apply a minimal theme to the plot generated by show_point_shapes() for a cleaner appearance. This demonstrates basic customization of the plot output. ```r show_point_shapes() + theme_minimal() ``` -------------------------------- ### Execute ggplot2 geom_point with geom_exec Source: https://r-packages.io/packages/ggpubr/geom_exec Demonstrates how to use geom_exec to call the geom_point function from ggplot2. This example maps 'mpg' to the x-axis, 'wt' to the y-axis, and 'cyl' to both size and color, using the mtcars dataset. ```R ggplot() + geom_exec(geom_point, data = mtcars, x = "mpg", y = "wt", size = "cyl", color = "cyl") ``` -------------------------------- ### Customize Bracket Tip Length Source: https://r-packages.io/packages/ggpubr/geom_bracket Shows how to customize the tip length of the bracket, controlling the length of the small lines at each end of the bracket. ```R ggboxplot(df, x = "dose", y = "len") + geom_bracket( xmin = "0.5", xmax = "1", y.position = 30, label = "t-test, p < 0.05", tip.length = c(0.2, 0.02) ) ``` -------------------------------- ### Plot Confidence Ellipses Source: https://r-packages.io/packages/ggpubr/stat_conf_ellipse This snippet shows the default arguments for the stat_conf_ellipse function, which is used to plot confidence ellipses around data barycenters. It requires no specific setup beyond loading the ggpubr package. ```r stat_conf_ellipse( mapping = NULL, data = NULL, geom = "path", position = "identity", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE, level = 0.95, npoint = 100, bary = TRUE, ... ) ``` -------------------------------- ### Basic Pipe Operator Usage Source: https://r-packages.io/packages/ggpubr/pipe Demonstrates the fundamental syntax of the pipe operator, chaining a left-hand side (lhs) to a right-hand side (rhs). ```R __ lhs %>% rhs ``` -------------------------------- ### Basic background_image function call Source: https://r-packages.io/packages/ggpubr/background_image This snippet shows the basic syntax for calling the background_image function with a raster image object. ```R background_image(raster.img) ``` -------------------------------- ### Draw Group Mean Points with ggscatter Source: https://r-packages.io/packages/ggpubr/stat_mean This example demonstrates how to use stat_mean to draw group mean points on a scatter plot created with ggscatter. It requires loading the mtcars dataset and converting the 'cyl' column to a factor. ```r # Load data data("mtcars") df <- mtcars df$cyl <- as.factor(df$cyl) # Scatter plot with ellipses and group mean points ggscatter(df, x = "wt", y = "mpg", color = "cyl", shape = "cyl", ellipse = TRUE)+ stat_mean(aes(color = cyl, shape = cyl), size = 4) ``` -------------------------------- ### Using Plotmath Expression for Labels Source: https://r-packages.io/packages/ggpubr/geom_bracket Illustrates using plotmath expressions for labels, allowing for mathematical notation like italicized p-values. ```R #Using plotmath expression ggboxplot(df, x = "dose", y = "len") + geom_bracket( xmin = "0.5", xmax = "1", y.position = 30, label = "list(~italic(p)<=0.001)", type = "expression", tip.length = c(0.2, 0.02) ) ``` -------------------------------- ### Load and Prepare Data for ggtext Source: https://r-packages.io/packages/ggpubr/ggtext Loads the mtcars dataset and prepares it for use with the ggtext function by converting 'cyl' to a factor and adding a 'name' column for labels. ```r # Load data data("mtcars") df <- mtcars df$cyl <- as.factor(df$cyl) df$name <- rownames(df) head(df[, c("wt", "mpg", "cyl")], 3) ``` -------------------------------- ### ggdotchart with Multiple Groups and Segments Source: https://r-packages.io/packages/ggpubr/ggdotchart Creates a dot plot for data with multiple groups, adding segments to connect related points. This example demonstrates using different color schemes and themes, and adjusting point size and segment appearance. ```r # Plot with multiple groups # +++++++++++++++++++++ # Create some data 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)) print(df2) ggdotchart(df2, x = "dose", y = "len", color = "supp", size = 3, add = "segment", add.params = list(color = "lightgray", size = 1.5), position = position_dodge(0.3), palette = "jco", ggtheme = theme_pubclean() ) ```