ggupset

repository·master·Indexed 18 days ago

https://github.com/const-ae/ggupset

An R package that extends ggplot2 to create UpSet plots, allowing users to visualize intersections of sets by replacing the standard x-axis with a combination matrix. It is designed to work with tidy 'list-columns' and integrates with the ggplot2 ecosystem via functions like scale_x_upset(), scale_x_mergelist(), and theme_combmatrix().

Tokens
2K
Snippets
9
Records
10
Agent score
14%

What's inside ggupset

  1. Compare `ggupset` with `UpSetR`

    master

    While UpSetR is a popular package for intersection visualization, ggupset is designed to integrate seamlessly with the ggplot2 ecosystem.

    Key Differences:

    • UpSetR: Provides a standalone plot with an additional view showing the overall size of each set. It requires data to be pivoted into a wide format.
    • ggupset: Works directly with ggplot2 objects and can be combined with any ggplot that uses a categorical x-axis. This allows for non-standard plots, such as combining an UpSet-style axis with violin plots or boxplots.
  2. Transform wide matrix data into list-columns for ggupset

    master

    UpSet plots in ggupset require data to be in a tidy format where categories are stored in a list-column. If you start with a wide matrix (e.g., genes vs. pathways), you must:

    1. Convert the matrix to a tidy tibble using as_tibble() and gather() (or pivot_longer()).
    2. Filter for TRUE memberships.
    3. Group by the primary identifier (e.g., Gene) and use summarize(Pathways = list(Pathway)) to create the required list-column.
    # 1. Tidy the matrix
    tidy_pathway_member <- gene_pathway_membership %>%
      as_tibble(rownames = "Pathway") %>%
      gather(Gene, Member, -Pathway) %>%
      filter(Member) %>%
      select(- Member)
    
    # 2. Create the list-column
    tidy_pathway_member %>%
      group_by(Gene) %>%
      summarize(Pathways = list(Pathway)) %>%
      ggplot(aes(x = Pathways)) +
        geom_bar() +
        scale_x_upset()
  3. Install ggupset

    master

    You can install the released version of ggupset from CRAN or get the latest development version directly from GitHub using devtools.

    # Download package from CRAN
    install.packages("ggupset")
    
    # Or get the latest version directly from GitHub
    devtools::install_github("const-ae/ggupset")
  4. Save `ggupset` plots using `ggsave()`

    master

    When saving plots that include a combination matrix, do not rely on ggsave()'s default behavior of saving last_plot(), as it may only capture the combination matrix component. Instead, explicitly assign your complete ggplot object to a variable and pass that variable to the plot argument in ggsave().

    pl <- tidy_movies %>% 
      ggplot(aes(x=Genres)) + 
      geom_bar() + 
      scale_x_upset(n_intersections = 20)
    
    ggsave("/tmp/movie_genre_barchart.png", plot = pl)
  5. Create an UpSet plot with scale_x_upset()

    master

    To create an UpSet plot, use ggplot2 with a list-column in your data. Map the list-column to the x aesthetic and apply scale_x_upset() to transform the x-axis into a combination matrix. This allows you to visualize intersections of categories (e.g., genres) instead of a standard categorical axis.

    library(ggplot2)
    library(tidyverse)
    library(ggupset)
    
    # Assuming tidy_movies has a list-column 'Genres'
    tidy_movies %>%
      distinct(title, year, length, .keep_all=TRUE) %>%
      ggplot(aes(x=Genres)) +
        geom_bar() +
        scale_x_upset(n_intersections = 20)
  6. Style the UpSet combination matrix with theme_combmatrix()

    master

    To customize the appearance of the combination matrix (the grid of dots/lines below the bar plot), use theme_combmatrix(). This function provides control over various elements of the matrix panel.

    tidy_movies %>%
      distinct(title, year, length, .keep_all=TRUE) %>%
      ggplot(aes(x=Genres)) +
        geom_bar() +
        scale_x_upset(order_by = "degree") +
        theme_combmatrix(
          combmatrix.panel.point.color.fill = "green",
          combmatrix.panel.line.size = 0,
          combmatrix.label.make_space = FALSE
        )
  7. Use `scale_x_upset` for UpSet-style axes

    master

    The scale_x_upset function allows you to add an UpSet-style combination matrix axis to a ggplot object. It is particularly useful when your x-axis contains list-columns or combined categorical labels.

    Common parameters:

    • order_by: Determines the ordering of intersections (e.g., "degree" or "freq").
    • n_sets: Limits the number of sets shown.
    • n_intersections: Limits the number of intersections shown.
    • sets: A character vector specifying the sets to include.
    • position: The position of the axis (e.g., "top").
    • name: The name of the axis.
    ggplot(aes(x=Genres)) +
      geom_bar() +
      scale_x_upset(order_by = "degree", n_sets = 5)
  8. Customize combination matrix plots with `override_plotting_function`

    master

    For advanced customization beyond standard styling, axis_combmatrix provides an override_plotting_function parameter. This allows you to pass a custom function that receives a data frame (df) and returns a ggplot object to be plotted in place of the standard combination matrix.

    The input df typically contains the following columns:

    • labels: The combination labels.
    • single_label: The individual set labels.
    • id: Integer ID.
    • labels_split: A list of the individual labels within the combination.
    • at: The x-axis position.
    • observed: Logical indicating if the combination exists.
    • index: The row index for the combination.

    Warning: This is an advanced feature and should be used with caution.

    axis_combmatrix(sep = "-", override_plotting_function = function(df){
      ggplot(df, aes(x= at, y= single_label)) +
        geom_rect(aes(fill= index %% 2 == 0), ymin=df$index-0.5, ymax=df$index+0.5, xmin=0, xmax=1) +
        geom_point(aes(color= observed), size = 3) +
        # ... additional ggplot layers ...
    })
  9. Use scale_x_mergelist() and axis_combmatrix() for flexible labeling

    master

    If you prefer not to use the full UpSet matrix, you can use alternative scaling methods:

    • scale_x_mergelist(sep = "-"): Automatically collapses list elements into a single delimited string (e.g., "Action-Animation") to be used as categorical axis labels.
    • axis_combmatrix(sep = "-"): Replaces axis labels with a combination matrix, which can be used in conjunction with scale_x_mergelist() to improve readability.
    # Using merged list labels with a combination matrix
    tidy_movies %>%
      distinct(title, year, length, .keep_all=TRUE) %>%
      ggplot(aes(x=Genres)) +
        geom_bar() +
        scale_x_mergelist(sep = "-") +
        axis_combmatrix(sep = "-")
  10. Order UpSet plot categories by degree

    master

    The scale_x_upset() function allows you to automatically order the categories and genres. Use the order_by argument set to "degree" to order them based on the number of intersections.

    tidy_movies %>%
      distinct(title, year, length, .keep_all=TRUE) %>%
      ggplot(aes(x=Genres)) +
        geom_bar() +
        scale_x_upset(order_by = "degree")