### Apply label repulsion with ggrepel Source: https://github.com/slowkow/ggrepel/blob/master/docs/reference/position_nudge_repel.md Examples demonstrating standard label repulsion and the use of nudging to adjust starting positions. ```r df <- data.frame( x = c(1,3,2,5), y = c("a","c","d","c") ) ggplot(df, aes(x, y)) + geom_point() + geom_text_repel(aes(label = y)) ``` ```r ggplot(df, aes(x, y)) + geom_point() + geom_text_repel( aes(label = y), min.segment.length = 0, position = position_nudge_repel(x = 0.1, y = 0.15) ) ``` ```r # The values for x and y can be vectors ggplot(df, aes(x, y)) + geom_point() + geom_text_repel( aes(label = y), min.segment.length = 0, position = position_nudge_repel( x = c(0.1, 0, -0.1, 0), y = c(0.1, 0.2, -0.1, -0.2) ) ) ``` ```r # We can also use geom_text_repel() with arguments nudge_x, nudge_y ggplot(df, aes(x, y)) + geom_point() + geom_text_repel( aes(label = y), min.segment.length = 0, nudge_x = 0.1, nudge_y = 0.15 ) ``` ```r # The arguments nudge_x, nudge_y also accept vectors ggplot(df, aes(x, y)) + geom_point() + geom_text_repel( aes(label = y), min.segment.length = 0, nudge_x = c(0.1, 0, -0.1, 0), nudge_y = c(0.1, 0.2, -0.1, -0.2) ) ``` -------------------------------- ### Advanced Examples with ggpp Source: https://github.com/slowkow/ggrepel/blob/master/docs/articles/examples.md Demonstrates how to leverage the ggpp package with ggrepel for advanced label positioning and control. ```APIDOC ## Advanced examples The ggrepel package works well with the [ggpp](https://docs.r4photobiology.info/ggpp/) package! For more advanced ggrepel examples, check out the [ggpp examples](https://docs.r4photobiology.info/ggpp/articles/nudge-examples.html) by Pedro Aphalo. In that article, Pedro shows how to use nudging functions from the [ggpp](https://docs.r4photobiology.info/ggpp/) package to achieve greater control over label positions. The [ggpp examples](https://docs.r4photobiology.info/ggpp/articles/nudge-examples.html) page describes how to use many advanced functions, including: - [`position_nudge_to()`](https://docs.r4photobiology.info/ggpp/reference/position_nudge_to.html) - [`position_nudge_center()`](https://docs.r4photobiology.info/ggpp/reference/position_nudge_center.html) - [`position_nudge_line()`](https://docs.r4photobiology.info/ggpp/reference/position_nudge_line.html) - [`position_nudge_keep()`](https://docs.r4photobiology.info/ggpp/reference/position_nudge_keep.html) - and many more! ``` -------------------------------- ### Example: Hide Labels Source: https://github.com/slowkow/ggrepel/blob/master/docs/articles/examples.md A practical example demonstrating how to hide specific labels by setting their aesthetic values to an empty string. ```APIDOC ## Examples ### Hide some of the labels Set labels to the empty string `""` to hide them. All data points repel the non-empty labels. ```r set.seed(42) dat2 <- subset(mtcars, wt > 3 & wt < 4) # Hide all of the text labels. dat2$car <- "" ``` ``` -------------------------------- ### Install ggrepel development version Source: https://github.com/slowkow/ggrepel/blob/master/docs/articles/ggrepel.md Installation command for the latest development version from GitHub using devtools. ```r # Use the devtools package # install.packages("devtools") devtools::install_github("slowkow/ggrepel") ``` -------------------------------- ### Advanced ggrepel configuration examples Source: https://github.com/slowkow/ggrepel/blob/master/docs/reference/geom_text_repel.html Demonstrates customizing font families, aesthetic mappings, and segment drawing behavior. ```R p + geom_text_repel(family = "Times New Roman", box.padding = 0.5) # Add aesthetic mappings p + geom_text_repel(aes(alpha=wt, size=mpg)) p + geom_label_repel(aes(fill=factor(cyl)), colour="white", segment.colour="black") # Draw all line segments p + geom_text_repel(min.segment.length = 0) # Omit short line segments (default behavior) p + geom_text_repel(min.segment.length = 0.5) ``` -------------------------------- ### Adjusting label starting positions with position_nudge_repel Source: https://context7.com/slowkow/ggrepel/llms.txt Demonstrates how to nudge labels from their original data points while maintaining correct segment connections. Includes examples for fixed nudging, vector-based nudging, and integration with stat_summary. ```r library(ggplot2) library(ggrepel) df <- data.frame( x = c(1, 3, 2, 5), y = c("a", "c", "d", "c") ) # Basic nudge - move all labels by fixed amount ggplot(df, aes(x, y, label = y)) + geom_point() + geom_text_repel( min.segment.length = 0, position = position_nudge_repel(x = 0.1, y = 0.15) ) # Vector nudge - different offset for each point ggplot(df, aes(x, y, label = y)) + geom_point() + geom_text_repel( min.segment.length = 0, position = position_nudge_repel( x = c(0.1, 0, -0.1, 0), y = c(0.1, 0.2, -0.1, -0.2) ) ) # Alternative: use nudge_x/nudge_y arguments directly ggplot(df, aes(x, y, label = y)) + geom_point() + geom_text_repel( min.segment.length = 0, nudge_x = 0.1, nudge_y = 0.15 ) # Using with stat_summary ggplot(mtcars, aes(factor(cyl), mpg)) + stat_summary(fun = "mean", geom = "col", fill = "gray90") + stat_summary( aes(label = round(after_stat(y))), fun = "mean", geom = "text_repel", min.segment.length = 0, position = position_nudge_repel(y = -2) ) ``` -------------------------------- ### Install ggrepel from CRAN Source: https://github.com/slowkow/ggrepel/blob/master/docs/articles/ggrepel.md Standard installation command for the ggrepel package. ```r install.packages("ggrepel") ``` -------------------------------- ### Install ggrepel Source: https://github.com/slowkow/ggrepel/blob/master/README.md Commands for installing the package from CRAN or the development version from GitHub. ```r # The easiest way to get ggrepel is to install it from CRAN: install.packages("ggrepel") # Or get the the development version from GitHub: ``` -------------------------------- ### Install ggrepel development version from GitHub Source: https://github.com/slowkow/ggrepel/blob/master/docs/index.html Install the latest development version of ggrepel directly from GitHub using the devtools package. Ensure devtools is installed first. ```R # install.packages("devtools") devtools::install_github("slowkow/ggrepel") ``` -------------------------------- ### Handle C++ array initialization Source: https://github.com/slowkow/ggrepel/blob/master/NEWS.md Example of C++ syntax that caused compiler errors in older clang versions. ```cpp v[i] = {0,0} ``` -------------------------------- ### Always show all labels with max.overlaps = Inf Source: https://github.com/slowkow/ggrepel/blob/master/docs/articles/examples.md This example compares the default `max.overlaps = 10` with `max.overlaps = Inf` to ensure all labels are displayed, even when they have many overlaps. It also shows how to set this option globally. ```r set.seed(42) n <- 15 dat4 <- data.frame( x = rep(1, length.out = n), y = rep(1, length.out = n), label = letters[1:n] ) # Set it globally: options(ggrepel.max.overlaps = Inf) p1 <- ggplot(dat4, aes(x, y, label = label)) + geom_point() + geom_label_repel(box.padding = 0.5, max.overlaps = 10) + labs(title = "max.overlaps = 10 (default)") p2 <- ggplot(dat4, aes(x, y, label = label)) + geom_point() + geom_label_repel(box.padding = 0.5) + labs(title = "max.overlaps = Inf") gridExtra::grid.arrange(p1, p2, ncol = 2) ``` -------------------------------- ### Repel text labels from data points Source: https://github.com/slowkow/ggrepel/blob/master/docs/articles/examples.md This example shows how to repel text labels from data points. It also highlights how to color points based on whether they have a label. ```r ix_label <- c(2, 3, 14) dat2$car[ix_label] <- rownames(dat2)[ix_label] ggplot(dat2, aes(wt, mpg, label = car)) + geom_text_repel() + geom_point(color = ifelse(dat2$car == "", "grey50", "red")) ``` -------------------------------- ### Use geom_label_repel Source: https://context7.com/slowkow/ggrepel/llms.txt Examples of adding repelling labels with background rectangles, including customization of fills, borders, and padding. ```r library(ggplot2) library(ggrepel) set.seed(42) dat <- subset(mtcars, wt > 2.75 & wt < 3.45) dat$car <- rownames(dat) # Basic label with background ggplot(dat, aes(wt, mpg, label = car)) + geom_point(color = "red") + geom_label_repel() # Customized labels with colored fills and borders ggplot(dat, aes(wt, mpg, label = car, fill = factor(cyl))) + geom_point() + geom_label_repel( color = "white", # Text color label.padding = 0.25, # Padding inside label box label.r = 0.15, # Corner radius label.size = 0.25, # Border width linewidth = 0.5, # Border line width linetype = "solid", # Border line type min.segment.length = 0, # Always show segments segment.color = "grey50" ) # Labels without borders (linewidth = 0) ggplot(dat, aes(wt, mpg, label = car)) + geom_point(color = "red") + geom_label_repel( fill = "lightblue", linewidth = 0 # Hide border completely ) ``` -------------------------------- ### Expand scale for label room Source: https://github.com/slowkow/ggrepel/blob/master/docs/articles/examples.md This example shows how to expand the plot scale using `scale_x_continuous` with `expand = expansion(mult = 0.5)` to provide more room for repelled text labels. ```r set.seed(42) d <- data.frame( x1 = 1, y1 = rnorm(10), x2 = 2, y2 = rnorm(10), lab = state.name[1:10] ) p <- ggplot(d, aes(x1, y1, xend = x2, yend = y2, label = lab, col = lab)) + geom_segment(size = 1) + guides(color = "none") + theme(axis.title.x = element_blank()) + geom_text_repel( nudge_x = -0.2, direction = "y", hjust = "right" ) + geom_text_repel( aes(x2, y2), nudge_x = 0.1, direction = "y", hjust = "left" ) p ``` ```r p + scale_x_continuous( breaks = 1:2, labels = c("Dimension 1", "Dimension 2"), expand = expansion(mult = 0.5) ) ``` -------------------------------- ### Labeling with Unicode Characters Source: https://github.com/slowkow/ggrepel/blob/master/docs/articles/examples.md ggrepel can handle Unicode characters for labels. This example demonstrates using Japanese characters. ```r library(ggrepel) set.seed(42) dat <- data.frame( x = runif(32), y = runif(32), label = strsplit( x = "原文篭毛與美篭母乳布久思毛與美夫君志持此岳尓菜採須兒家吉閑名思毛", split = "" )[[1]] ) ``` -------------------------------- ### Nudging label positions with geom_text_repel Source: https://github.com/slowkow/ggrepel/blob/master/docs/reference/geom_text_repel.md Adjust the initial starting positions of labels using 'nudge_x' and 'nudge_y'. This allows for fine-tuning the placement before repulsive forces are applied. ```r # Nudge the starting positions p + geom_text_repel(nudge_x = ifelse(mtcars$cyl == 6, 1, 0), nudge_y = ifelse(mtcars$cyl == 6, 8, 0)) ``` -------------------------------- ### Repel text labels with max.overlaps = Inf Source: https://github.com/slowkow/ggrepel/blob/master/docs/articles/examples.md This example demonstrates repelling text labels from a large dataset (10,000 points) while ensuring no labels are discarded, even with numerous overlaps, by setting `max.overlaps = Inf`. ```r set.seed(42) dat3 <- rbind( data.frame( wt = rnorm(n = 10000, mean = 3), mpg = rnorm(n = 10000, mean = 19), car = "" ), dat2[,c("wt", "mpg", "car")] ) ggplot(dat3, aes(wt, mpg, label = car)) + geom_point(data = dat3[dat3$car == "",], color = "grey50") + geom_text_repel(box.padding = 0.5, max.overlaps = Inf) + geom_point(data = dat3[dat3$car != "",], color = "red") ``` -------------------------------- ### Plotting rich text and images with geom_marquee_repel (ragg_png) Source: https://github.com/slowkow/ggrepel/blob/master/docs/articles/examples.md Demonstrates using geom_marquee_repel to plot markdown-formatted text and images. This example uses dev="ragg_png" for improved rendering quality. ```r logo <- "https://cran.r-project.org/Rlogo.svg" # Note: width values are in "npc" units (proportion of panel width). # Use values between 0 and 1 (e.g., 0.3 = 30% of panel width) df <- data.frame( x = c(0, 4.9, 5, 5.1, 10), y = c(0, 4.9, 5, 5.1, 10), labels = c( "Some {.blue *italic blue*} text", "Other {.red **bold red**} text", "More {.purple ~strikethrough~} text", "# Title\nBody text", paste0("![](", logo, ")") ), widths = c(0.3, 0.3, 0.3, 0.3, 0.3) # npc units, so 0.3 = 30% of panel width ) # In this knitr chunk, we are using dev="ragg_png" like so: # {r marquee, echo=TRUE, fig.width=6, fig.height=5, dev="ragg_png"} ggplot(df, aes(x, y, label = labels, width = widths)) + geom_marquee_repel( box.padding = unit(5, "mm"), seed = 1 ) + labs(title = 'dev="ragg_png"') ``` -------------------------------- ### Do not repel labels from data points Source: https://github.com/slowkow/ggrepel/blob/master/docs/articles/examples.md This example demonstrates how to prevent text labels from repelling away from data points by setting `point.size = NA`. Labels will still repel from each other and plot edges. ```r set.seed(42) ggplot(dat, aes(wt, mpg, label = car)) + geom_point(color = "red") + geom_text_repel(point.size = NA) ``` -------------------------------- ### Retrieve R session information Source: https://github.com/slowkow/ggrepel/blob/master/docs/articles/examples.md Display the current R environment and loaded package versions. ```R sessionInfo() ``` -------------------------------- ### Apply modified coordinate systems Source: https://github.com/slowkow/ggrepel/blob/master/docs/articles/examples.html Examples of using ggrepel with flipped, limited, or transformed coordinate axes. ```R p <- ggplot(mtcars, aes(wt, mpg, label = rownames(mtcars))) + geom_text_repel() + geom_point(color = 'red') # Swap the x and y coordinates p + coord_flip() ``` ```R # Limit the x-axis to values <= 3 p + scale_x_continuous(limits = c(NA, 3)) ``` ```R # Transform the y-axis with a pseudo log transformation p + coord_trans(y = scales::pseudo_log_trans(base = 2, sigma = 0.1)) ``` -------------------------------- ### Create animated label movement Source: https://github.com/slowkow/ggrepel/blob/master/docs/articles/examples.md Generate a GIF animation showing the iterative label repulsion process using the animation package. ```R library(ggrepel) library(animation) plot_frame <- function(n) { set.seed(42) p <- ggplot(mtcars, aes(wt, mpg, label = rownames(mtcars))) + geom_text_repel( size = 5, force = 1, max.iter = n ) + geom_point(color = "red") + # theme_minimal(base_size = 16) + labs(title = n) print(p) } xs <- ceiling(1.18^(1:52)) # xs <- ceiling(1.4^(1:26)) xs <- c(xs, rep(xs[length(xs)], 15)) # plot(xs) saveGIF( lapply(xs, function(i) { plot_frame(i) }), interval = 0.15, ani.width = 800, ani.heigth = 600, movie.name = "animated.gif" ) ``` -------------------------------- ### Use geom_marquee_repel Source: https://context7.com/slowkow/ggrepel/llms.txt Examples of adding repelling rich text labels that support Markdown formatting and embedded images. ```r library(ggplot2) library(ggrepel) # install.packages("marquee") # Rich text with Markdown formatting df <- data.frame( x = c(1, 2, 3, 4), y = c(1, 2, 3, 4), labels = c( "Some {.blue *italic blue*} text", "Other {.red **bold red**} text", "More {.purple ~strikethrough~} text", "# Title\nBody text" ), widths = c(0.3, 0.3, 0.3, 0.3) # Width in npc units (0-1) ) # Use dev="ragg_png" for best quality ggplot(df, aes(x, y, label = labels, width = widths)) + geom_marquee_repel( box.padding = unit(5, "mm"), seed = 1 ) # With embedded images logo <- "https://cran.r-project.org/Rlogo.svg" df2 <- data.frame( x = c(1, 5, 10), y = c(1, 5, 10), labels = c( "Plain text", "**Bold text**", paste0("![](", logo, ")") ), widths = c(0.2, 0.2, 0.3) ) ggplot(df2, aes(x, y, label = labels, width = widths)) + geom_point(color = "red") + geom_marquee_repel(box.padding = unit(3, "mm")) ``` -------------------------------- ### Configure label repulsion and visibility Source: https://github.com/slowkow/ggrepel/blob/master/docs/reference/geom_text_repel.html Adjust segment visibility and point repulsion settings for text labels. ```R p + geom_text_repel(segment.colour = NA) ``` ```R # Repel just the labels and totally ignore the data points p + geom_text_repel(point.size = NA) ``` ```R # Hide some of the labels, but repel from all data points mtcars$label <- rownames(mtcars) mtcars$label[1:15] <- "" p + geom_text_repel(data = mtcars, aes(wt, mpg, label = label)) ``` -------------------------------- ### Justify multiple lines with geom_label_repel Source: https://github.com/slowkow/ggrepel/blob/master/docs/articles/examples.md Similar to geom_text_repel, this example shows text justification with geom_label_repel, which adds a background box to the labels. ```r p + geom_label_repel( data = labelInfo, mapping = aes(x, y, label = g), size = 5, hjust = c(1, 0), nudge_x = c(-0.05, 0.05), arrow = arrow(length = unit(2, "mm"), ends = "last", type = "closed") ) ``` -------------------------------- ### Use geom_text_repel Source: https://context7.com/slowkow/ggrepel/llms.txt Examples of adding repelling text labels to ggplot2 plots, including basic usage, advanced parameter customization, and selective label hiding. ```r library(ggplot2) library(ggrepel) # Basic usage - labels repel from each other and points ggplot(mtcars, aes(wt, mpg, label = rownames(mtcars))) + geom_point(color = "red") + geom_text_repel() # With customization - control repulsion, segments, and constraints set.seed(42) dat <- subset(mtcars, wt > 2.75 & wt < 3.45) dat$car <- rownames(dat) ggplot(dat, aes(wt, mpg, label = car, color = factor(cyl))) + geom_point() + geom_text_repel( box.padding = 0.5, # Padding around text boxes point.padding = 0.3, # Padding around data points min.segment.length = 0, # Always draw segments max.overlaps = Inf, # Show all labels regardless of overlaps force = 2, # Increase repulsion force force_pull = 1, # Attraction to original point max.time = 1, # Max seconds for positioning max.iter = 10000, # Max iterations seed = 42 # Reproducible positioning ) # Hide some labels by setting them to empty string mtcars$label <- rownames(mtcars) mtcars$label[1:25] <- "" # Hide first 25 labels ggplot(mtcars, aes(wt, mpg, label = label)) + geom_point(color = ifelse(mtcars$label == "", "grey50", "red")) + geom_text_repel(max.overlaps = Inf) ``` -------------------------------- ### Initialize position_nudge_repel Source: https://github.com/slowkow/ggrepel/blob/master/docs/reference/position_nudge_repel.md Basic usage of the position_nudge_repel function to define horizontal and vertical offsets. ```r position_nudge_repel(x = 0, y = 0) ``` -------------------------------- ### Using stat_summary with position_nudge_repel Source: https://github.com/slowkow/ggrepel/blob/master/docs/articles/examples.md Compares the behavior of position_nudge() and position_nudge_repel() when used with stat_summary() and geom_text_repel. Use position_nudge_repel() to maintain original data point positions. ```r p <- ggplot(mtcars, aes(factor(cyl), mpg)) + stat_summary( fill = "gray90", colour = "black", fun = "mean", geom = "col" ) p1 <- p + stat_summary( aes(label = round(after_stat(y))), fun = "mean", geom = "text_repel", min.segment.length = 0, # always draw segments position = position_nudge(y = -2) ) + labs(title = "position_nudge()") p2 <- p + stat_summary( aes(label = round(after_stat(y))), fun = "mean", geom = "text_repel", min.segment.length = 0, # always draw segments position = position_nudge_repel(y = -2) ) + labs(title = "position_nudge_repel()") gridExtra::grid.arrange(p1, p2, ncol = 2) ``` -------------------------------- ### Increasing Space with Margin Source: https://github.com/slowkow/ggrepel/blob/master/docs/reference/element_text_repel.md Shows how to increase the available space for text labels by setting the margin for element_text_repel. This is useful when default spacing is insufficient. ```r p + theme(axis.text.y.left = element_text_repel(margin = margin(r = 20))) ``` -------------------------------- ### Use expect_equal for testing Source: https://github.com/slowkow/ggrepel/blob/master/NEWS.md Replace identical checks with expect_equal in test suites. ```R expect_equal(x, y) ``` -------------------------------- ### Disable repulsion from plot edges Source: https://github.com/slowkow/ggrepel/blob/master/docs/articles/examples.md This example shows how to disable repulsion from plot (panel) edges by setting `xlim` or `ylim` to `Inf` or `-Inf`. `NA` indicates the edge of the panel. ```r set.seed(42) ggplot(dat, aes(wt, mpg, label = car)) + geom_point(color = "red") + geom_text_repel( # Repel away from the left edge, not from the right. xlim = c(NA, Inf), # Do not repel from top or bottom edges. ylim = c(-Inf, Inf) ) ``` -------------------------------- ### Verbose Output for Label Placement Source: https://context7.com/slowkow/ggrepel/llms.txt Enables verbose output using `verbose = TRUE` to display timing and overlap statistics during label placement. Useful for debugging and performance tuning. Set `seed` for reproducibility. ```r library(ggplot2) library(ggrepel) # Enable verbose output to see algorithm progress p <- ggplot(mtcars, aes(wt, mpg, label = rownames(mtcars), colour = factor(cyl))) + geom_point() p + geom_text_repel( verbose = TRUE, # Print timing info seed = 123, # Reproducible max.time = 0.1, # Limit to 0.1 seconds max.iter = Inf, # No iteration limit size = 3 ) # Output: "ggrepel: 0.100000s elapsed for 1180 iterations, 46 overlaps..." # Global verbose setting options(verbose = TRUE) # Enable for all ggrepel calls options(verbose = FALSE) # Disable (default) ``` -------------------------------- ### Customize Curved Segments and Arrows in R Source: https://context7.com/slowkow/ggrepel/llms.txt Demonstrates how to style segments with curvature, inflection, and arrows using geom_text_repel. ```r library(ggplot2) library(ggrepel) set.seed(42) dat <- subset(mtcars, wt > 2.75 & wt < 3.45) dat$car <- rownames(dat) # Curved segments ggplot(dat, aes(wt, mpg, label = car)) + geom_point(color = "red") + geom_text_repel( nudge_x = 0.15, nudge_y = 1, segment.curvature = -0.1, # Negative = left curve, positive = right segment.ncp = 3, # Control points for smoothness segment.angle = 20 # Skew toward start (< 90) or end (> 90) ) # Sharp angled segments with arrows cars <- c("Volvo 142E", "Merc 230") ggplot(dat, aes(wt, mpg, label = ifelse(car %in% cars, car, ""))) + geom_point(color = "red") + geom_text_repel( point.padding = 0.2, nudge_x = 0.15, nudge_y = 0.5, segment.curvature = -1e-20, # Near-zero for sharp angle arrow = arrow(length = unit(0.015, "npc")) ) # Inflected curves (S-shaped) ggplot(dat, aes(wt, mpg, label = car)) + geom_point(color = "red") + geom_text_repel( nudge_x = 0.3, direction = "y", hjust = 0, segment.curvature = -0.1, segment.square = FALSE, # Oblique placement segment.inflect = TRUE # Add inflection point ) # Different arrow types and fills df <- mtcars[1:8,] df$car <- rownames(df) ggplot(df, aes(wt, mpg, label = car)) + geom_point(color = "red") + geom_text_repel( min.segment.length = 0, segment.colour = "blue", arrow = arrow(length = unit(0.05, "npc"), type = "closed"), box.padding = 1.5, arrow.fill = "green" # Custom arrow head fill color ) ``` -------------------------------- ### Create Animated GIF with ggrepel Source: https://github.com/slowkow/ggrepel/blob/master/docs/articles/examples.html This code generates an animated GIF where labels are repelled using ggrepel. It requires the 'animation' and 'ggrepel' libraries. The animation iterates through different repulsion forces. ```r library(ggrepel) library(animation) plot_frame <- function(n) { set.seed(42) p <- ggplot(mtcars, aes(wt, mpg, label = rownames(mtcars))) + geom_text_repel( size = 5, force = 1, max.iter = n ) + geom_point(color = "red") + labs(title = n) print(p) } xs <- ceiling(1.18^(1:52)) xs <- c(xs, rep(xs[length(xs)], 15)) saveGIF( lapply(xs, function(i) { plot_frame(i) }), interval = 0.15, ani.width = 800, ani.heigth = 600, movie.name = "animated.gif" ) ``` -------------------------------- ### Creating a Word Cloud with ggrepel Source: https://github.com/slowkow/ggrepel/blob/master/docs/articles/examples.md Generate a word cloud by setting all labels to the origin (0,0) and disabling the pull force. Adjust force and force_pull for repulsion and label attraction. ```r set.seed(42) ggplot(mtcars) + geom_text_repel( aes( label = rownames(mtcars), size = mpg > 15, colour = factor(cyl), x = 0, y = 0 ), force_pull = 0, # do not pull text toward the point at (0,0) max.time = 0.5, max.iter = 1e5, max.overlaps = Inf, segment.color = NA, point.padding = NA ) + theme_void() + theme(strip.text = element_text(size = 16)) + facet_wrap(~ factor(cyl)) + scale_color_discrete(name = "Cylinders") + scale_size_manual(values = c(2, 3)) + theme( strip.text = element_blank(), panel.border = element_rect(size = 0.2, fill = NA) ) ``` -------------------------------- ### Disable clipping to allow labels beyond panel edges Source: https://github.com/slowkow/ggrepel/blob/master/docs/articles/examples.md This example demonstrates disabling clipping using `coord_cartesian(clip = "off")` to allow labels to extend beyond the panel edges, combined with `xlim` and `ylim` set to `Inf`. ```r set.seed(42) ggplot(dat, aes(wt, mpg, label = car)) + geom_point(color = "red") + coord_cartesian(clip = "off") + geom_label_repel(fill = "white", xlim = c(-Inf, Inf), ylim = c(-Inf, Inf)) ``` -------------------------------- ### Global Configuration for Label Overlaps Source: https://github.com/slowkow/ggrepel/blob/master/docs/articles/examples.html How to manage label visibility and overlap limits using the max.overlaps parameter. ```APIDOC ## Global Configuration: max.overlaps ### Description Controls the maximum number of overlaps allowed before a label is discarded. Setting this to Inf ensures all labels are displayed. ### Usage - **Global Option**: options(ggrepel.max.overlaps = Inf) - **Local Argument**: max.overlaps = Inf (passed to geom_text_repel or geom_label_repel) ``` -------------------------------- ### Apply Shadows and Glow Effects in R Source: https://context7.com/slowkow/ggrepel/llms.txt Uses bg.color and bg.r to create a background shadow effect for improved text legibility. ```r library(ggplot2) library(ggrepel) set.seed(42) dat <- subset(mtcars, wt > 2.75 & wt < 3.45) dat$car <- rownames(dat) # White text with dark shadow ggplot(dat, aes(wt, mpg, label = car)) + geom_point(color = "red") + geom_text_repel( color = "white", # Text color bg.color = "grey30", # Shadow color bg.r = 0.15 # Shadow radius ) ``` -------------------------------- ### geom_text_repel and geom_label_repel Parameters Source: https://github.com/slowkow/ggrepel/blob/master/docs/reference/geom_text_repel.html Configuration parameters for controlling label repulsion, positioning, and appearance in ggrepel. ```APIDOC ## Parameters - **point.padding** (unit/number) - Optional - Amount of padding around labeled point. Defaults to 0. - **label.r** (unit/number) - Optional - Radius of rounded corners. Defaults to 0.15. - **label.size** (number) - Optional - Size of label border, in mm. - **min.segment.length** (unit/number) - Optional - Skip drawing segments shorter than this. Defaults to 0.5. - **arrow** (specification) - Optional - Specification for arrow heads. - **force** (number) - Optional - Force of repulsion between overlapping text labels. Defaults to 1. - **force_pull** (number) - Optional - Force of attraction between a text label and its corresponding data point. Defaults to 1. - **max.time** (number) - Optional - Maximum number of seconds to try to resolve overlaps. Defaults to 0.5. - **max.iter** (number) - Optional - Maximum number of iterations to try to resolve overlaps. Defaults to 10000. - **max.overlaps** (number) - Optional - Exclude text labels when they overlap too many other things. Defaults to 10. - **nudge_x, nudge_y** (numeric) - Optional - Horizontal and vertical adjustments to nudge the starting position. - **xlim, ylim** (numeric) - Optional - Limits for the x and y axes. - **na.rm** (logical) - Optional - If FALSE, removes missing values with a warning. Defaults to FALSE. - **show.legend** (logical) - Optional - Should this layer be included in the legends? Defaults to NA. - **direction** (string) - Optional - "both", "x", or "y" – direction in which to adjust position of labels. - **seed** (numeric) - Optional - Random seed passed to set.seed. Defaults to NA. - **verbose** (logical) - Optional - If TRUE, some diagnostics of the repel algorithm are printed. - **inherit.aes** (logical) - Optional - If FALSE, overrides the default aesthetics. ``` -------------------------------- ### Handle Variable Point Sizes in R Source: https://context7.com/slowkow/ggrepel/llms.txt Configures repulsion based on point size using continuous_scale to ensure labels avoid larger points appropriately. ```r library(ggplot2) library(ggrepel) set.seed(42) dat <- subset(mtcars, wt > 2.75 & wt < 3.45) dat$car <- rownames(dat) # Custom palette for point sizes my_pal <- function(range = c(1, 6)) { force(range) function(x) scales::rescale(x, to = range, from = c(0, 1)) } # Apply same scale to both point size and label repulsion distance ggplot(dat, aes(wt, mpg, label = car)) + geom_point(aes(size = cyl), alpha = 0.6) + continuous_scale( aesthetics = c("size", "point.size"), scale_name = "size", palette = my_pal(c(2, 15)), guide = guide_legend(override.aes = list(label = "")) ) + geom_text_repel( aes(point.size = cyl), # Repel based on point size size = 5, # Text label font size point.padding = 0, min.segment.length = 0, box.padding = 0.3 ) # Ignore point sizes (repel from label centers only) ggplot(dat, aes(wt, mpg, label = car)) + geom_point(color = "red") + geom_text_repel(point.size = NA) # Labels don't repel from points ``` -------------------------------- ### Configure global overlap limits Source: https://github.com/slowkow/ggrepel/blob/master/NEWS.md Set global options to control label overlap behavior. ```R option(ggrepel.max.overlaps = Inf) ``` -------------------------------- ### Google Analytics gtag.js Configuration Source: https://github.com/slowkow/ggrepel/blob/master/docs/ISSUE_TEMPLATE.html This snippet configures Google Analytics using gtag.js. It initializes the dataLayer and sets up the tracking ID. ```javascript window.dataLayer = window.dataLayer || []; function gtag(){ dataLayer.push(arguments); } gtag('js', new Date()); gtag('config', 'UA-15531613-2'); ``` -------------------------------- ### Constrain Label Placement in R Source: https://context7.com/slowkow/ggrepel/llms.txt Shows how to limit label positioning using xlim, ylim, and max.overlaps to manage density. ```r library(ggplot2) library(ggrepel) set.seed(42) dat <- subset(mtcars, wt > 2.75 & wt < 3.45) dat$car <- rownames(dat) # Constrain labels to right side of plot x_limits <- c(3, NA) # NA means edge of panel ggplot(dat, aes(wt, mpg, label = car, fill = factor(cyl))) + geom_vline(xintercept = 3, linetype = 3) + geom_point() + geom_label_repel( color = "white", xlim = x_limits, # Labels only where x >= 3 point.padding = NA, # Ignore points in repulsion box.padding = 0.1, arrow = arrow(length = unit(0.03, "npc"), type = "closed", ends = "first") ) # Disable repulsion from edges (labels can overlap edges) ggplot(dat, aes(wt, mpg, label = car)) + geom_point(color = "red") + geom_text_repel( xlim = c(NA, Inf), # Repel from left only ylim = c(-Inf, Inf) # Don't repel from top/bottom ) # Allow labels outside plot area ggplot(dat, aes(wt, mpg, label = car)) + geom_point(color = "red") + coord_cartesian(clip = "off") + # Disable clipping geom_label_repel( fill = "white", xlim = c(-Inf, Inf), ylim = c(-Inf, Inf) ) # Control max overlaps (default = 10, Inf = show all) options(ggrepel.max.overlaps = Inf) # Global setting ggplot(dat, aes(wt, mpg, label = car)) + geom_point() + geom_label_repel( box.padding = 0.5, max.overlaps = 10 # Override global, hide labels with >10 overlaps ) ``` -------------------------------- ### Reproduce ggrepel issue Source: https://github.com/slowkow/ggrepel/blob/master/docs/ISSUE_TEMPLATE.md Minimal code snippet required to demonstrate the reported issue. ```r ggplot(...) + geom_text_repel(...) ``` -------------------------------- ### Custom Line Types and Arrows Source: https://github.com/slowkow/ggrepel/blob/master/docs/articles/examples.md Demonstrates using different `segment.linetype` values and `arrow()` configurations for segment appearance. ```r set.seed(42) cars <- c("Volvo 142E", "Merc 230") ggplot(dat, aes(wt, mpg, label = ifelse(car %in% cars, car, ""))) + geom_point(color = "red") + geom_text_repel( point.padding = 0.2, nudge_x = .15, nudge_y = .5, segment.linetype = 6, segment.curvature = -1e-20, arrow = arrow(length = unit(0.015, "npc")) ) ``` -------------------------------- ### Draw All or No Line Segments Source: https://github.com/slowkow/ggrepel/blob/master/docs/articles/examples.md Use `min.segment.length = 0` to draw all segments, regardless of length. Use `min.segment.length = Inf` to draw no segments. ```r p <- ggplot(dat, aes(wt, mpg, label = car)) + geom_point(color = "red") p1 <- p + geom_text_repel(min.segment.length = 0, seed = 42, box.padding = 0.5) + labs(title = "min.segment.length = 0") p2 <- p + geom_text_repel(min.segment.length = Inf, seed = 42, box.padding = 0.5) + labs(title = "min.segment.length = Inf") gridExtra::grid.arrange(p1, p2, ncol = 2) ``` -------------------------------- ### Configure element_text_repel for crowded axes Source: https://github.com/slowkow/ggrepel/blob/master/docs/reference/element_text_repel.html Demonstrates how to use element_text_repel to handle overlapping axis labels, adjust margins for spacing, and customize segment appearance. ```R # A plot with a crowded y-axis p <- ggplot(mtcars, aes(mpg, rownames(mtcars))) + geom_col() + coord_cartesian(ylim = c(-32, 64)) + theme(axis.text.y = element_text_repel()) # By default there isn't enough space to draw distinctive lines p # The available space can be increased by setting the margin p + theme(axis.text.y.left = element_text_repel(margin = margin(r = 20))) # For secondary axis positions at the top and right, the `position` argument # should be set accordingly p + scale_y_discrete(position = "right") + theme(axis.text.y.right = element_text_repel( margin = margin(l = 20), position = "right" )) # Using segment settings and matching tick colour p + theme( axis.text.y.left = element_text_repel( margin = margin(r = 20), segment.curvature = -0.1, segment.inflect = TRUE, segment.colour = "red" ), axis.ticks.y.left = element_line(colour = "red") ) ``` -------------------------------- ### Justify multiple lines of text with hjust Source: https://github.com/slowkow/ggrepel/blob/master/docs/articles/examples.md Demonstrates how to justify multiple lines of text using the hjust aesthetic with geom_text_repel. The nudge_x argument is used to offset the labels. ```r p <- ggplot() + coord_cartesian(xlim=c(0,1), ylim=c(0,1)) + theme_void() labelInfo <- data.frame( x = c(0.45, 0.55), y = c(0.5, 0.5), g = c( "I'd like very much to be\nright justified.", "And I'd like to be\nleft justified." ) ) p + geom_text_repel( data = labelInfo, mapping = aes(x, y, label = g), size = 5, hjust = c(1, 0), nudge_x = c(-0.05, 0.05), arrow = arrow(length = unit(2, "mm"), ends = "last", type = "closed") ) ```