### Install ComplexUpset from GitHub Source: https://github.com/krassowski/complex-upset/blob/master/README.md Use this R code to install the development version of the ComplexUpset package directly from GitHub. Ensure the devtools package is installed first. ```R if(!require(devtools)) install.packages("devtools") devtools::install_github("krassowski/complex-upset") ``` -------------------------------- ### create_upset_abc_example() Source: https://github.com/krassowski/complex-upset/blob/master/_autodocs/api-reference/utility-functions.md Generates a simple three-set example data frame suitable for quick testing and demonstration. ```APIDOC ## create_upset_abc_example() ### Description Generates a simple three-set example data frame suitable for quick testing and demonstration. ### Return Value A data frame with binary columns A, B, C representing three sets, pre-populated with example data. ### Example ```r example_data <- create_upset_abc_example() upset(example_data, intersect = c('A', 'B', 'C')) ``` ``` -------------------------------- ### Install ComplexUpset from CRAN Source: https://github.com/krassowski/complex-upset/blob/master/README.md Install the stable release of the ComplexUpset package from CRAN using this R command. This version may be slightly behind the GitHub version. ```R install.packages('ComplexUpset') ``` -------------------------------- ### Prepare for Visual Tests Source: https://github.com/krassowski/complex-upset/blob/master/README.md Run this script to generate updated test cases for visual testing after changing or adding examples. ```bash scripts/prepare_for_tests.sh ``` -------------------------------- ### Create Example Data for Upset Plot Source: https://github.com/krassowski/complex-upset/blob/master/_autodocs/api-reference/utility-functions.md Generates a simple three-set example data frame. Use this for quick testing and demonstration of upset plots. ```r example_data <- create_upset_abc_example() upset(example_data, intersect = c('A', 'B', 'C')) ``` -------------------------------- ### Install Python Requirements Source: https://github.com/krassowski/complex-upset/blob/master/vignettes/Prepare_Python.ipynb Installs pandas, pydataset, and rpy2 using pip. These are essential for data manipulation and R integration. ```bash pip install pandas pydataset rpy2 ``` -------------------------------- ### Load ComplexUpset Package Source: https://github.com/krassowski/complex-upset/blob/master/_autodocs/README.md This snippet demonstrates how to load the ComplexUpset package in R. Ensure the package is installed before running this command. ```r library(ComplexUpset) ``` -------------------------------- ### Error Handling Guide Source: https://github.com/krassowski/complex-upset/blob/master/_autodocs/MANIFEST.txt Guide to understanding and resolving error messages, including conditions, scenarios, and source code tracing. ```APIDOC ## Error Handling Guide This guide assists in understanding and resolving errors encountered with ComplexUpset. ### Error Messages and Conditions - Lists specific error messages and the conditions under which they occur. ### Trigger Scenarios - Describes scenarios that lead to specific errors. ### Fix Recommendations - Provides recommendations for resolving identified errors. ### Source Code Tracing - Includes references to source code locations for each error condition. ``` -------------------------------- ### Create Example Data and UpSet Plot Source: https://github.com/krassowski/complex-upset/blob/master/_autodocs/README.md Demonstrates how to create a sample data frame and generate an UpSet plot using the 'upset' function. This is a basic example for visualizing set intersections. ```r data <- data.frame( A = c(TRUE, TRUE, FALSE, TRUE, FALSE), B = c(TRUE, FALSE, TRUE, TRUE, FALSE), C = c(FALSE, TRUE, TRUE, FALSE, TRUE) ) # Create UpSet plot upset(data, intersect = c('A', 'B', 'C')) ``` -------------------------------- ### Example Data Frame for ComplexUpset Source: https://github.com/krassowski/complex-upset/blob/master/_autodocs/INDEX.md This is an example of a data frame that can be used as input for ComplexUpset functions. It includes binary set indicator columns and an optional annotation column. ```r data.frame( A = c(TRUE, FALSE, TRUE), B = c(TRUE, TRUE, FALSE), C = c(FALSE, TRUE, TRUE), value = c(10, 20, 15) # Optional for annotations ) ``` -------------------------------- ### Fix Invalid Guides Parameter Value Source: https://github.com/krassowski/complex-upset/blob/master/_autodocs/errors.md Corrects a typo in the 'guides' parameter, which must be one of 'keep', 'collect', 'over', or NULL. ```r upset(data, intersect = c('A', 'B', 'C'), guides = 'combine') # ERROR: typo ``` ```r upset(data, intersect = c('A', 'B', 'C'), guides = 'collect') # Correct ``` -------------------------------- ### R: Example scenario for hyphenated name conflict Source: https://github.com/krassowski/complex-upset/blob/master/_autodocs/errors.md Illustrates a data frame setup that leads to a name conflict error due to hyphenated and underscored set names. ```r # This causes error if column names are 'my-set' and 'my_set' data <- data.frame( 'my-set' = c(TRUE, FALSE, TRUE), 'my_set' = c(FALSE, TRUE, TRUE) # Conflict! ) upset(data, intersect = c('my-set', 'my_set')) # ERROR ``` -------------------------------- ### Multiple Queries with Different Styles Source: https://github.com/krassowski/complex-upset/blob/master/_autodocs/api-reference/upset_query.md This example shows how to combine multiple queries with distinct highlighting styles and component targeting to create complex visual effects in the UpSet plot. ```r upset( data, intersect = c('A', 'B', 'C'), queries = list( upset_query(intersect = c('A', 'B'), fill = 'red', only_components = 'intersections_matrix'), upset_query(set = 'C', fill = 'blue', only_components = 'Intersection size'), upset_query(group = 'degree-2', color = 'green', alpha = 0.7) ) ) ``` -------------------------------- ### Install ComplexUpset using Conda Source: https://github.com/krassowski/complex-upset/blob/master/README.md Install the ComplexUpset R package using conda or mamba from the conda-forge channel. This is a convenient option for users managing their environments with conda. ```shell conda install -c conda-forge r-complexupset ``` -------------------------------- ### Filter by Size and Degree Source: https://github.com/krassowski/complex-upset/blob/master/_autodocs/api-reference/upset_data.md This example shows how to filter the processed data using `min_size` and `min_degree` parameters. It also demonstrates custom sorting of intersections by degree and cardinality. ```r processed <- upset_data( data, intersect = c('A', 'B', 'C'), min_size = 1, min_degree = 2, sort_intersections_by = c('degree', 'cardinality') ) ``` -------------------------------- ### Comprehensive API Reference Source: https://github.com/krassowski/complex-upset/blob/master/_autodocs/MANIFEST.txt Detailed documentation for all 29 exported functions, including signatures, parameter types, default values, return specifications, and usage examples. ```APIDOC ## API Reference This section details all 29 exported functions of the ComplexUpset library. ### Function Signatures - All functions include their complete signatures. ### Parameters - Parameter types and default values are fully documented. ### Return Values - Return value specifications are provided for each function. ### Usage Examples - Each function includes at least one usage example. ``` -------------------------------- ### Basic Venn Diagram Implementation Source: https://github.com/krassowski/complex-upset/blob/master/vignettes/Examples.ipynb This example demonstrates a simple implementation of Venn diagrams using the 'arrange_venn' function. It takes similar input to 'upset()' but supports a maximum of three sets. Requires 'R' environment and 'movies', 'genres' data. ```R %%R movies_subset = head(movies, 300) genres_subset = c('Comedy', 'Drama', 'Action') movies_subset$good_rating = movies_subset$rating > mean(movies_subset$rating) arranged = arrange_venn(movies_subset, sets=genres_subset) ``` -------------------------------- ### Get Citation for ComplexUpset Package Source: https://github.com/krassowski/complex-upset/blob/master/_autodocs/START_HERE.md Use this R code snippet to retrieve the citation information for the ComplexUpset package. ```r # In R: citation('ComplexUpset') ``` -------------------------------- ### Highlight a Specific Intersection Source: https://github.com/krassowski/complex-upset/blob/master/_autodocs/api-reference/upset_query.md This example shows how to highlight a precise intersection of sets ('A' AND 'B') using the 'intersect' parameter of upset_query(). ```r upset( data, intersect = c('A', 'B', 'C'), queries = list( upset_query(intersect = c('A', 'B'), color = 'blue', fill = 'lightblue') ) ) ``` -------------------------------- ### Minimal Set Size Display Source: https://github.com/krassowski/complex-upset/blob/master/_autodocs/api-reference/upset_set_size.md Creates a minimal set size display with a narrower bar width and a specified fill color. This example shows how to achieve a compact visual representation of set sizes. ```r upset( data, intersect = c('A', 'B', 'C'), set_sizes = upset_set_size( geom = geom_bar(width = 0.4, color = 'black'), mapping = aes(fill = 'gray50') ) ) ``` -------------------------------- ### Highlight a Specific Set Source: https://github.com/krassowski/complex-upset/blob/master/_autodocs/api-reference/upset_query.md This example demonstrates how to highlight all intersections containing a specific set ('A'). It uses the 'set' parameter of upset_query(). ```r library(ggplot2) library(ComplexUpset) # Create sample data data <- data.frame( A = c(TRUE, TRUE, FALSE, TRUE, FALSE), B = c(TRUE, FALSE, TRUE, TRUE, FALSE), C = c(FALSE, TRUE, TRUE, FALSE, TRUE) ) # Highlight a specific set (all intersections containing A) upset( data, intersect = c('A', 'B', 'C'), queries = list( upset_query(set = 'A', fill = 'red') ) ) ``` -------------------------------- ### Different Ratio Calculation: Inclusive Intersection / Union Source: https://github.com/krassowski/complex-upset/blob/master/_autodocs/api-reference/intersection_ratio.md Example of calculating the ratio using 'inclusive_intersection' as the numerator mode and 'union' as the denominator mode. This changes how the ratio is computed. ```r upset( data, intersect = c('A', 'B', 'C'), base_annotations = list( 'Ratio' = intersection_ratio( mode = 'intersect', denominator_mode = 'union' ) ) ) ``` -------------------------------- ### Apply Highlighting to Specific Components Source: https://github.com/krassowski/complex-upset/blob/master/_autodocs/api-reference/upset_query.md This example demonstrates how to apply highlighting only to specified plot components, such as the 'intersections_matrix' and 'Intersection size', using the 'only_components' parameter. ```r upset( data, intersect = c('A', 'B', 'C'), queries = list( upset_query( set = 'A', color = 'red', only_components = c('intersections_matrix', 'Intersection size') ) ) ) ``` -------------------------------- ### matrix_frame Example Data Source: https://github.com/krassowski/complex-upset/blob/master/_autodocs/types.md An example of the long-format data frame for intersection membership, showing which groups are part of specific intersections. ```text intersection group value 1 A-B-C A TRUE 2 A-B-C B TRUE 3 A-B-C C TRUE 4 A-B-C D FALSE 5 A-B A TRUE 6 A-B B TRUE 7 A-B C FALSE ``` -------------------------------- ### Highlight by Degree Group Source: https://github.com/krassowski/complex-upset/blob/master/_autodocs/api-reference/upset_query.md This example highlights all intersections belonging to a specific degree group (e.g., 2-way intersections) using the 'group' parameter of upset_query(). ```r upset( data, intersect = c('A', 'B', 'C'), queries = list( upset_query(group = 'degree-2', fill = 'orange', alpha = 0.5) ) ) ``` -------------------------------- ### Upset Plot with Annotations Relative to All Observed Values Source: https://github.com/krassowski/complex-upset/blob/master/vignettes/Examples.ipynb This example demonstrates creating an upset plot where annotations are displayed relative to all observed values. It's useful for understanding the proportion of each category across the entire dataset. Requires 'R' environment and 'movies', 'genres' data. ```R %%R -w 800 -h 500 upset( movies, genres, name='genre', width_ratio=0.1, min_size=100, annotations =list( 'MPAA Rating'=list( aes=aes(x=intersection, fill=mpaa), geom=list( geom_bar(stat='count', position='fill', na.rm=TRUE), geom_text( aes(label=!!aes_percentage(relative_to='all'), color=ifelse(mpaa == 'R', 'show', 'hide') ), stat='count', position=position_fill(vjust = .5) ), scale_y_continuous(labels=scales::percent_format()), show_hide_scale, rating_scale ) ) ) ) ``` -------------------------------- ### Statistical Testing Setup for Upset Plot Data Source: https://github.com/krassowski/complex-upset/blob/master/_autodocs/configuration.md Prepares data for Upset plot analysis by specifying intersections, minimum size, columns to ignore for testing, and overriding default statistical tests for specific variable types. ```r upset_test( data, intersect = c('A', 'B', 'C'), min_size = 5, ignore = c('sample_id', 'date'), tests = list( continuous_var = t.test, # Override default test for specific variable categorical_var = chisq.test ) ) ``` -------------------------------- ### Combining Multiple Upset Plots with Patchwork Source: https://github.com/krassowski/complex-upset/blob/master/vignettes/Examples.ipynb This example demonstrates how to combine two upset plots side-by-side using the 'patchwork' library in R. It requires 'patchwork' and 'ComplexUpset' libraries, along with 'movies' and 'genres' data. The plots use different subsets of the data. ```R %%R -w 800 -h 500 library(patchwork) annotations = list( 'MPAA Rating'=list( aes=aes(x=intersection, fill=mpaa), geom=list( geom_bar(stat='count', position='fill') ) ) ) set.seed(0) # for replicable example only data_1 = movies[sample(nrow(movies), 100), ] data_2 = movies[sample(nrow(movies), 100), ] u1 = upset(data_1, genres, min_size=5, base_annotations=annotations) u2 = upset(data_2, genres, min_size=5, base_annotations=annotations) (u1 | u2) + plot_layout(guides='collect') ``` -------------------------------- ### Create ABC Example Venn Diagram Source: https://github.com/krassowski/complex-upset/blob/master/vignettes/Examples.ipynb Generates a Venn diagram for three sets (A, B, C) using ggplot2 and complex-upset's geom_venn functions. This snippet sets up the base Venn diagram with regions, points, circles, and labels. ```R abc_data = create_upset_abc_example() abc_venn = ( ggplot(arrange_venn(abc_data)) + coord_fixed() + theme_void() + scale_color_venn_mix(abc_data) ) ( abc_venn + geom_venn_region(data=abc_data, alpha=0.05) + geom_point(aes(x=x, y=y, color=region), size=1) + geom_venn_circle(abc_data) + geom_venn_label_set(abc_data, aes(label=region)) + geom_venn_label_region( abc_data, aes(label=size), outwards_adjust=1.75, position=position_nudge(y=0.2) ) + scale_fill_venn_mix(abc_data, guide='none') ) ``` -------------------------------- ### Annotate with Barplots for Proportions Source: https://github.com/krassowski/complex-upset/blob/master/vignettes/Examples.ipynb Use barplots within annotations to visualize the proportions of categorical variables across intersections. This example shows how to display the distribution of MPAA ratings, using custom color scales and percentage formatting for the y-axis. ```R upset( movies, genres, annotations = list( 'MPAA Rating'=( ggplot(mapping=aes(fill=mpaa)) + geom_bar(stat='count', position='fill') + scale_y_continuous(labels=scales::percent_format()) + scale_fill_manual(values=c( 'R'='#E41A1C', 'PG'='#377EB8', 'PG-13'='#4DAF4A', 'NC-17'='#FF7F00' )) + ylab('MPAA Rating') ) ), width_ratio=0.1 ) ``` -------------------------------- ### Create Basic UpSet Plot Source: https://github.com/krassowski/complex-upset/blob/master/_autodocs/START_HERE.md Demonstrates how to create a basic UpSet plot using binary data. Requires the ComplexUpset library to be loaded. ```R library(ComplexUpset) # Binary data: which sets each element belongs to data <- data.frame( A = c(TRUE, TRUE, FALSE, TRUE, FALSE), B = c(TRUE, FALSE, TRUE, TRUE, FALSE), C = c(FALSE, TRUE, TRUE, FALSE, TRUE) ) # Create UpSet plot upset(data, intersect = c('A', 'B', 'C')) ``` -------------------------------- ### Positioning Set Sizes and Legends Source: https://github.com/krassowski/complex-upset/blob/master/vignettes/Examples.ipynb Demonstrates how to change the position of the set size bars to the right and move the legends to overlap the set sizes. This involves specifying the position in `upset_set_size` and using the `guides='over'` argument. ```R upset( movies, genres, min_size=10, width_ratio=0.3, set_sizes=( upset_set_size( geom=geom_bar( aes(fill=mpaa, x=group), width=0.8 ), position='right' ) ), # moves legends over the set sizes guides='over' ) ``` -------------------------------- ### Type and Configuration Reference Source: https://github.com/krassowski/complex-upset/blob/master/_autodocs/MANIFEST.txt Reference for object structures, classes, parameters, data formats, and configuration options available in the ComplexUpset library. ```APIDOC ## Type and Configuration Reference This section covers the data structures and configuration settings for ComplexUpset. ### Object Structures and Classes - Documentation for all object structures and classes used within the library. ### Parameters and Defaults - Details on all available parameters and their default values. ### Data Formats - Specifications for expected data formats. ### Configuration Options - Comprehensive reference for all configuration parameters. ``` -------------------------------- ### Customizing Segment Appearance in Intersection Matrix Source: https://github.com/krassowski/complex-upset/blob/master/_autodocs/api-reference/intersection_matrix.md Modifies the appearance of the connecting segments, making them thicker (linewidth = 2) and red. This example customizes the 'segment' parameter. ```r upset( data, intersect = c('A', 'B', 'C'), matrix = intersection_matrix( segment = geom_segment(linewidth = 2, color = 'red') ) ) ``` -------------------------------- ### Manage Visual Tests Source: https://github.com/krassowski/complex-upset/blob/master/README.md Execute this script to validate the generated images for visual tests. ```bash scripts/manage_visual_tests.sh ``` -------------------------------- ### Handle Non-Logical Columns for Set Indicators Source: https://github.com/krassowski/complex-upset/blob/master/_autodocs/errors.md Shows how to manage non-logical values in set indicator columns, which are automatically coerced to binary. The warning can be controlled using `warn_when_converting`. ```r data <- data.frame( A = c(2, 1, 0), # Non-standard binary B = c(1, 0, 1) ) upset(data, intersect = c('A', 'B')) # WARNING: Converting non-logical columns to binary: A, B ``` ```r # Suppress with explicit parameter upset(data, intersect = c('A', 'B'), warn_when_converting = FALSE) # Or enable specific warning upset(data, intersect = c('A', 'B'), warn_when_converting = TRUE) ``` -------------------------------- ### Customizing Point Size and Color in Intersection Matrix Source: https://github.com/krassowski/complex-upset/blob/master/_autodocs/api-reference/intersection_matrix.md Customizes the intersection matrix to use larger, navy-colored points. This example shows how to modify the 'geom' parameter of intersection_matrix(). ```r upset( data, intersect = c('A', 'B', 'C'), matrix = intersection_matrix( geom = geom_point(size = 4, color = 'navy') ) ) ``` -------------------------------- ### Show Intersection Size and Ratio Annotations Source: https://github.com/krassowski/complex-upset/blob/master/vignettes/Examples.ipynb Illustrates how to display both the absolute intersection size and the intersection-to-union size ratio. This helps in identifying intersections that are larger than expected by chance. ```R upset( movies, genres, name='genre', width_ratio=0.1, min_size=10, base_annotations=list( 'Intersection size'=intersection_size(), 'Intersection ratio'=intersection_ratio() ) ) ``` -------------------------------- ### Upset Plot with Minimum Size and Wrapping Source: https://github.com/krassowski/complex-upset/blob/master/vignettes/Examples.ipynb Creates an upset plot with a minimum intersection size of 10 and enables text wrapping. This example shows how empty groups are automatically dropped. ```R upset(movies, genres, name='genre', width_ratio=0.1, min_size=10, wrap=TRUE, set_sizes=FALSE) ``` -------------------------------- ### Get Symbolic Reference to Size Column with get_size_mode Source: https://github.com/krassowski/complex-upset/blob/master/_autodocs/api-reference/utility-functions.md Retrieves the symbolic column name for intersection sizes of a specific mode. Enables using different size modes in custom annotations without hardcoding column names. ```r library(ggplot2) # Get symbol for distinct intersection size distinct_size <- get_size_mode('distinct') ``` -------------------------------- ### Load and Inspect Movies Dataset Source: https://github.com/krassowski/complex-upset/blob/master/vignettes/Prepare_Python.ipynb Loads the 'movies' dataset using pydataset and displays the first 3 rows transposed. This prepares the data for analysis. ```python from pydataset import data as load_data movies = load_data('movies').dropna() movies.head(3).T ``` -------------------------------- ### ComplexUpset Library Import Source: https://github.com/krassowski/complex-upset/blob/master/_autodocs/INDEX.md This is the standard R import statement required to load the ComplexUpset library and make its functions available for use. ```r library(ComplexUpset) ``` -------------------------------- ### Run Upset Test with Custom Tests Source: https://github.com/krassowski/complex-upset/blob/master/vignettes/Examples.ipynb Applies custom statistical tests (e.g., Chi-squared for 'mpaa', ANOVA for 'budget') to the upset analysis. This allows for more specific statistical modeling. ```R %R head(upset_test(movies, genres, tests=custom_tests)) ``` -------------------------------- ### Applying Reversed Log Scale to Set Sizes Source: https://github.com/krassowski/complex-upset/blob/master/vignettes/Examples.ipynb Shows how to apply a reversed log scale to the y-axis for set sizes, which is useful when dealing with data that spans several orders of magnitude. Requires the `reverse_log_trans()` function. ```R upset( movies, genres, width_ratio=0.1, min_size=10, set_sizes=( upset_set_size() + theme(axis.text.x=element_text(angle=90)) + scale_y_continuous(trans=reverse_log_trans()) ), queries=list(upset_query(set='Drama', fill='blue')) ) ``` -------------------------------- ### Customizing Set Sizes with Different Geoms Source: https://github.com/krassowski/complex-upset/blob/master/vignettes/Examples.ipynb Demonstrates how to use different geoms like geom_bar and geom_point for visualizing set sizes. This allows for varied visual representations of the data within the upset plot. ```R upset( movies, genres, width_ratio=0.5, max_size=100, min_size=15, wrap=TRUE, set_sizes=upset_set_size( geom=geom_bar(width=0.4) ) ) ``` ```R upset( movies, genres, width_ratio=0.5, max_size=100, min_size=15, wrap=TRUE, set_sizes=upset_set_size( geom=geom_point( stat='count', color='blue' ) ) ) ``` ```R upset( movies, genres, width_ratio=0.5, max_size=100, min_size=15, wrap=TRUE, set_sizes=( upset_set_size( geom=geom_point(stat='count'), mapping=aes(y=..count../max(..count..)), ) + ylab('Size relative to the largest') ) ) ``` -------------------------------- ### Create Annotated UpSet Plot with Queries in R Source: https://github.com/krassowski/complex-upset/blob/master/README.md This R code demonstrates how to generate an UpSet plot using the ComplexUpset package. It includes custom annotations for 'Length' and 'Rating', and defines specific queries to highlight subsets of the data. Ensure ggplot2movies is installed for the 'movies' dataset. ```R library(ggplot2) library(ComplexUpset) if(!require(ggplot2movies)) install.packages('ggplot2movies') movies = ggplot2movies::movies genres = c('Action', 'Animation', 'Comedy', 'Drama', 'Documentary', 'Romance') upset( movies, genres, annotations = list( 'Length'=ggplot(mapping=aes(x=intersection, y=length)) + geom_boxplot(), 'Rating'=ggplot(mapping=aes(x=intersection, y=rating)) # if you do not want to install ggbeeswarm, you can use geom_jitter + ggbeeswarm::geom_quasirandom(aes(color=log10(votes))) + geom_violin(width=1.1, alpha=0.5) ), queries=list( upset_query( intersect=c('Drama', 'Comedy'), color='red', fill='red', only_components=c('intersections_matrix', 'Intersection size') ), upset_query( set='Drama', fill='blue' ), upset_query( intersect=c('Romance', 'Drama'), fill='yellow', only_components=c('Length') ) ), min_size=10, width_ratio=0.1 ) ``` -------------------------------- ### upset_default_themes Source: https://github.com/krassowski/complex-upset/blob/master/_autodocs/api-reference/utility-functions.md Creates a copy of upset_themes with all component themes modified with the provided theme arguments. Useful for global theme changes applied across all components. ```APIDOC ## upset_default_themes(...) ### Description Creates a copy of upset_themes with all component themes modified with the provided theme arguments. Useful for global theme changes applied across all components. ### Function Signature ```r upset_default_themes(...) ``` ### Parameters #### Parameters - **...** (—) - Default: — - Arguments passed to ggplot2::theme() ### Return Value A list of themes (like upset_themes) with all themes modified by the specified arguments. ### Example ```r # Make all text bold and larger upset( data, intersect = c('A', 'B', 'C'), themes = upset_default_themes(text = element_text(size = 14, face = 'bold')) ) # Remove gridlines everywhere upset( data, intersect = c('A', 'B', 'C'), themes = upset_default_themes(panel.grid = element_blank()) ) ``` ``` -------------------------------- ### Load rpy2 IPython Extension Source: https://github.com/krassowski/complex-upset/blob/master/vignettes/Prepare_Python.ipynb Loads the rpy2 IPython extension, enabling the use of R magic commands within a Jupyter Notebook. ```python %%capture %load_ext rpy2.ipython ``` -------------------------------- ### Basic upset_set_size() Usage Source: https://github.com/krassowski/complex-upset/blob/master/_autodocs/api-reference/upset_set_size.md Demonstrates the default configuration for the set size barplot. This is the most basic way to include set sizes in an upset plot. ```r library(ggplot2) library(ComplexUpset) data <- data.frame( A = c(TRUE, TRUE, FALSE, TRUE, FALSE), B = c(TRUE, FALSE, TRUE, TRUE, FALSE), C = c(FALSE, TRUE, TRUE, FALSE, TRUE), group = c('X', 'Y', 'X', 'Y', 'Z') ) upset( data, intersect = c('A', 'B', 'C') ) ``` -------------------------------- ### Basic UpSet Plot with Default Matrix Source: https://github.com/krassowski/complex-upset/blob/master/_autodocs/api-reference/intersection_matrix.md Demonstrates a basic UpSet plot using default settings for the intersection matrix. Requires the ComplexUpset and ggplot2 libraries. ```r library(ggplot2) library(ComplexUpset) # Create sample data data <- data.frame( A = c(TRUE, TRUE, FALSE, TRUE, FALSE), B = c(TRUE, FALSE, TRUE, TRUE, FALSE), C = c(FALSE, TRUE, TRUE, FALSE, TRUE) ) # Basic usage with defaults upset( data, intersect = c('A', 'B', 'C') ) ``` -------------------------------- ### Load and Inspect Movies Dataset Source: https://github.com/krassowski/complex-upset/blob/master/vignettes/Prepare_R.ipynb Loads the 'movies' dataset from the ggplot2 package and displays the first 3 rows to understand its structure. ```r movies = as.data.frame(ggplot2movies::movies) head(movies, 3) ``` -------------------------------- ### Apply Global Theme Modifications to All Upset Plot Components Source: https://github.com/krassowski/complex-upset/blob/master/_autodocs/api-reference/utility-functions.md Illustrates using upset_default_themes to apply consistent theme modifications, such as text size and boldness, across all components of an upset plot. ```r upset( data, intersect = c('A', 'B', 'C'), themes = upset_default_themes(text = element_text(size = 14, face = 'bold')) ) ``` -------------------------------- ### Simplify Annotation Panel Creation with upset_annotate Source: https://github.com/krassowski/complex-upset/blob/master/_autodocs/api-reference/utility-functions.md Simplifies annotation panel creation by automatically mapping x to intersection and y to a specified variable. Use for simple annotation cases. ```r library(ggplot2) data <- data.frame( A = c(TRUE, TRUE, FALSE, TRUE), B = c(TRUE, FALSE, TRUE, TRUE), value = c(10, 20, 15, 25) ) # Simple annotation with upset_annotate() upset( data, intersect = c('A', 'B'), annotations = list( 'Value' = upset_annotate('value', geom_boxplot()) ) ) # Equivalent to full specification: upset( data, intersect = c('A', 'B'), annotations = list( 'Value' = ggplot(mapping = aes(x = intersection, y = value)) + geom_boxplot() ) ) ``` -------------------------------- ### Adding Custom Themes for Annotations Source: https://github.com/krassowski/complex-upset/blob/master/vignettes/Examples.ipynb Incorporate custom themes for specific annotation panels like 'Rating' and 'Length' by modifying the upset_themes list. ```R upset( movies, genres, annotations = list( 'Length'=list( aes=aes(x=intersection, y=length), geom=geom_boxplot(na.rm=TRUE) ), 'Rating'=list( aes=aes(x=intersection, y=rating), geom=list( geom_jitter(aes(color=log10(votes)), na.rm=TRUE), geom_violin(alpha=0.5, na.rm=TRUE) ) ) ), min_size=10, width_ratio=0.1, themes=modifyList( upset_themes, list(Rating=theme_void(), Length=theme()) ) ) ``` -------------------------------- ### Customizing Bar Position with intersection_size() Source: https://github.com/krassowski/complex-upset/blob/master/_autodocs/api-reference/intersection_size.md Demonstrates how to alter the bar positioning using the 'position' parameter (e.g., position_dodge()) and adjust bar width with the 'width' parameter in intersection_size(). ```r upset( data, intersect = c('A', 'B', 'C'), base_annotations = list( 'Intersection size' = intersection_size( position = position_dodge(), fill = 'steelblue', width = 0.8 ) ) ) ``` -------------------------------- ### Customizing Label Positioning and Appearance Source: https://github.com/krassowski/complex-upset/blob/master/_autodocs/api-reference/intersection_ratio.md Demonstrates how to adjust label positioning using 'bar_number_threshold', and customize label text size and color. 'text' and 'text_colors' parameters are used for this. ```r upset( data, intersect = c('A', 'B', 'C'), base_annotations = list( 'Intersection ratio' = intersection_ratio( bar_number_threshold = 0.5, text = list(size = 3.5), text_colors = c(on_background = 'gray30', on_bar = 'white') ) ) ) ``` -------------------------------- ### Customizing Bar Appearance with intersection_size() Source: https://github.com/krassowski/complex-upset/blob/master/_autodocs/api-reference/intersection_size.md Shows how to customize the fill and color of the intersection size bars using the fill and color parameters within intersection_size(). ```r upset( data, intersect = c('A', 'B', 'C'), base_annotations = list( 'Intersection size' = intersection_size( fill = 'steelblue', color = 'navy' ) ) ) ``` -------------------------------- ### Combining Multiple Intersection Matrix Customizations Source: https://github.com/krassowski/complex-upset/blob/master/_autodocs/api-reference/intersection_matrix.md Combines several customizations including point/segment appearance, outline colors, and mapping alpha based on intersection value. Demonstrates flexible configuration. ```r upset( data, intersect = c('A', 'B', 'C'), matrix = intersection_matrix( geom = geom_point(size = 3.5, color = 'steelblue'), segment = geom_segment(linewidth = 1.5, color = 'steelblue'), outline_color = list(active = 'steelblue', inactive = 'gray90'), mapping = aes(alpha = ifelse(value, 1, 0.3)) ) ) ``` -------------------------------- ### Basic intersection_ratio() Usage Source: https://github.com/krassowski/complex-upset/blob/master/_autodocs/api-reference/intersection_ratio.md Demonstrates the basic usage of intersection_ratio() with default settings in an upset plot. Requires ggplot2 and ComplexUpset libraries. ```r library(ggplot2) library(ComplexUpset) # Create sample data data <- data.frame( A = c(TRUE, TRUE, FALSE, TRUE, FALSE), B = c(TRUE, FALSE, TRUE, TRUE, FALSE), C = c(FALSE, TRUE, TRUE, FALSE, TRUE), value = c(10, 20, 15, 25, 30) ) # Basic usage with default settings upset( data, intersect = c('A', 'B', 'C'), base_annotations = list( 'Intersection ratio' = intersection_ratio() ) ) ``` -------------------------------- ### Configure Matrix Background Stripes with upset_stripes Source: https://github.com/krassowski/complex-upset/blob/master/_autodocs/api-reference/utility-functions.md Creates alternating background stripes in the intersection matrix to improve readability. Use custom colors or geoms for appearance. Can be disabled by passing FALSE to upset(). ```r library(ComplexUpset) library(ggplot2) data <- data.frame( A = c(TRUE, TRUE, FALSE), B = c(TRUE, FALSE, TRUE), C = c(FALSE, TRUE, TRUE) ) # Default stripes (white and light grey) upset(data, intersect = c('A', 'B', 'C')) # Custom stripe colors upset( data, intersect = c('A', 'B', 'C'), stripes = upset_stripes(colors = c('white', 'lightblue')) ) # Single color (no alternation) upset( data, intersect = c('A', 'B', 'C'), stripes = upset_stripes(colors = 'gray95') ) # No stripes upset(data, intersect = c('A', 'B', 'C'), stripes = FALSE) # Custom stripe appearance upset( data, intersect = c('A', 'B', 'C'), stripes = upset_stripes( colors = c('#f0f0f0', '#ffffff'), geom = geom_segment(size = 5, alpha = 0.5) ) ) ``` -------------------------------- ### Adding Custom Aesthetics with upset_set_size() Source: https://github.com/krassowski/complex-upset/blob/master/_autodocs/api-reference/upset_set_size.md Applies custom aesthetics like fill and alpha to the set size bars using the 'mapping' parameter. Note that custom aesthetics in 'mapping' can override geom defaults. ```r upset( data, intersect = c('A', 'B', 'C'), set_sizes = upset_set_size( mapping = aes(fill = 'steelblue', alpha = 0.8), geom = geom_bar(width = 0.6, color = 'navy') ) ) ``` -------------------------------- ### Retrieving Set Order Source: https://github.com/krassowski/complex-upset/blob/master/vignettes/Examples.ipynb Display the current order of sets. This is useful for understanding the default ordering before applying sorting or custom arrangements. ```R genres ``` -------------------------------- ### upset_data() Source: https://github.com/krassowski/complex-upset/blob/master/_autodocs/api-reference/upset_data.md Prepares and processes raw binary membership data into a structured format suitable for UpSet visualization. It handles data validation, transformation, filtering, sorting, and computation of intersection sizes across multiple region selection modes. ```APIDOC ## upset_data() ### Description Processes raw binary membership data into structured format suitable for UpSet visualization. Handles data validation, transformation, filtering, sorting, and computation of intersection sizes across multiple region selection modes. This is called automatically by upset() but can be used independently for advanced workflows. ### Function Signature ```r upset_data( data, intersect, min_size = 0, max_size = Inf, min_degree = 0, max_degree = Inf, n_intersections = NULL, keep_empty_groups = FALSE, warn_when_dropping_groups = FALSE, warn_when_converting = 'auto', sort_sets = 'descending', sort_intersections = 'descending', sort_intersections_by = 'cardinality', sort_ratio_numerator = 'exclusive_intersection', sort_ratio_denominator = 'inclusive_union', group_by = 'degree', mode = 'exclusive_intersection', size_columns_suffix = '_size', encode_sets = FALSE, max_combinations_datapoints_n = 10^10, intersections = 'observed' ) ``` ### Parameters #### Data Input - **data** (data.frame) - Required - Input dataframe with binary columns for set membership. - **intersect** (character vector) - Required - Column names representing sets (minimum 2 required). #### Filtering Parameters - **min_size** (numeric) - Optional - Default: 0 - Minimum number of observations in intersection to include. - **max_size** (numeric) - Optional - Default: Inf - Maximum number of observations in intersection to include. - **min_degree** (numeric) - Optional - Default: 0 - Minimum number of sets in intersection (degree >= min_degree). - **max_degree** (numeric) - Optional - Default: Inf - Maximum number of sets in intersection (degree <= max_degree). - **n_intersections** (integer) - Optional - Default: NULL - Exact number of largest intersections to show (overrides other limits). #### Grouping and Sorting Parameters - **keep_empty_groups** (logical) - Optional - Default: FALSE - Keep sets with no observations after filtering. - **warn_when_dropping_groups** (logical) - Optional - Default: FALSE - Issue warning when empty sets are removed. - **warn_when_converting** (logical/'auto') - Optional - Default: 'auto' - Warn if non-binary columns need conversion (auto: detect if values are 0/1). - **sort_sets** (character/logical) - Optional - Default: 'descending' - Sort set rows: 'ascending', 'descending', or FALSE. - **sort_intersections** (character/logical) - Optional - Default: 'descending' - Sort intersection columns: 'ascending', 'descending', or FALSE. - **sort_intersections_by** (character vector) - Optional - Default: 'cardinality' - Sorting method(s): 'cardinality' (size), 'degree' (number of sets), 'ratio', or combination. - **sort_ratio_numerator** (character) - Optional - Default: 'exclusive_intersection' - Mode for numerator when sorting by ratio. - **sort_ratio_denominator** (character) - Optional - Default: 'inclusive_union' - Mode for denominator when sorting by ratio. - **group_by** (character) - Optional - Default: 'degree' - Group intersections by: 'degree' (number of sets) or 'sets' (which sets). #### Mode and Encoding Parameters - **mode** (character) - Optional - Default: 'exclusive_intersection' - Region mode: 'exclusive_intersection'/'distinct', 'inclusive_intersection'/'intersect', 'exclusive_union', 'inclusive_union'/'union'. - **size_columns_suffix** (character) - Optional - Default: '_size' - Suffix for size columns (adjust if conflicts with data columns). - **encode_sets** (logical) - Optional - Default: FALSE - Encode set names as numbers to handle very long names (TRUE for upset(), FALSE for upset_data()). - **max_combinations_datapoints_n** (numeric) - Optional - Default: 10^10 - Fail-safe limit for intersections='all' to prevent memory issues. - **intersections** (character or list) - Optional - Default: 'observed' - 'observed' (present in data), 'all' (all possible), or list of specific intersections as list(c('A'), c('B'), c('A','B')). ### Return Value A list containing: - `matrix_frame`: Data frame with intersection membership matrix in long format. - `sorted`: List with sorted groups (sets) and intersections. - `plot_intersections_subset`: Intersections included in plot after filtering. - `plot_sets_subset`: Sets included in plot after filtering. - `sanitized_labels`: Sanitized column names (with hyphens replaced). - `non_sanitized_labels`: Original column names with mapping to sanitized names. - `with_sizes`: Data frame with size columns for all modes appended. - `data`: Processed input data frame. - All other metadata needed for upset() plotting. ### Usage Example ```r library(ComplexUpset) # Create sample binary data data <- data.frame( A = c(1, 1, 0, 1, 0), B = c(1, 0, 1, 1, 0), C = c(0, 1, 1, 0, 1), value = c(10, 20, 15, 25, 30) ) # Process data with defaults processed <- upset_data(data, intersect = c('A', 'B', 'C')) # Access processed data head(processed$matrix_frame) # Intersection membership in long format processed$sorted$groups # Sorted set names processed$plot_intersections_subset # Which intersections to display # Filter by size and degree processed <- upset_data( data, intersect = c('A', 'B', 'C'), min_size = 1, min_degree = 2, sort_intersections_by = c('degree', 'cardinality') ) # Show top 5 intersections processed <- upset_data( data, intersect = c('A', 'B', 'C'), n_intersections = 5 ) ``` ``` -------------------------------- ### Manually Set Fill Colors for Intersection Bars Source: https://github.com/krassowski/complex-upset/blob/master/vignettes/Examples.ipynb Illustrates how to manually set specific colors for the intersection bars using `scale_fill_manual` when filling by a variable. This allows for custom color schemes. ```R upset( movies, genres, base_annotations=list( 'Intersection size'=intersection_size( counts=FALSE, mapping=aes(fill=mpaa) ) + scale_fill_manual(values=c( 'R'='#E41A1C', 'PG'='#377EB8', 'PG-13'='#4DAF4A', 'NC-17'='#FF7F00' )) ), width_ratio=0.1 ) ``` -------------------------------- ### Customizing Text Appearance with intersection_size() Source: https://github.com/krassowski/complex-upset/blob/master/_autodocs/api-reference/intersection_size.md Illustrates advanced customization of count labels using the 'text' and 'text_mapping' parameters to control size, angle, and fontface within intersection_size(). ```r upset( data, intersect = c('A', 'B', 'C'), base_annotations = list( 'Intersection size' = intersection_size( text = list(size = 3.5, angle = 45), text_mapping = aes(fontface = 'bold') ) ) ) ``` -------------------------------- ### Adding Text Counts and Annotations to Set Sizes Source: https://github.com/krassowski/complex-upset/blob/master/vignettes/Examples.ipynb Adds text labels displaying the count directly on the bars and includes an additional annotation at a specific position. This requires disabling set encoding to allow annotation by name. ```R upset( movies, genres, min_size=10, width_ratio=0.3, encode_sets=FALSE, # for annotate() to select the set by name disable encoding set_sizes=( upset_set_size() + geom_text(aes(label=..count..), hjust=1.1, stat='count') # you can also add annotations on top of bars: + annotate(geom='text', label='@', x='Drama', y=850, color='white', size=3) + expand_limits(y=1100) + theme(axis.text.x=element_text(angle=90)) ) ) ``` -------------------------------- ### Set Size Calculation with Filtered Intersections Source: https://github.com/krassowski/complex-upset/blob/master/vignettes/Examples.ipynb Compares the default set size calculation with one that filters intersections based on criteria like `min_size`. This is useful when you want the set sizes to accurately reflect the filtered intersections. ```R upset( movies, genres, min_size=200, set_sizes=upset_set_size() ) | upset( movies, genres, min_size=200, set_sizes=upset_set_size(filter_intersections=TRUE) ) ``` -------------------------------- ### Customizing Bar Appearance with intersection_ratio() Source: https://github.com/krassowski/complex-upset/blob/master/_autodocs/api-reference/intersection_ratio.md Shows how to customize the fill, color, and alpha of the bars in the intersection ratio annotation. Pass additional parameters to geom_col(). ```r upset( data, intersect = c('A', 'B', 'C'), base_annotations = list( 'Intersection ratio' = intersection_ratio( fill = 'steelblue', color = 'navy', alpha = 0.8 ) ) ) ``` -------------------------------- ### Sorting Sets in Ascending Order Source: https://github.com/krassowski/complex-upset/blob/master/vignettes/Examples.ipynb Sort the sets in ascending order using `sort_sets='ascending'`. This arranges the primary sets alphabetically or by their natural order. ```R upset(movies, genres, width_ratio=0.1, sort_sets='ascending') ``` -------------------------------- ### Process Data with Defaults Source: https://github.com/krassowski/complex-upset/blob/master/_autodocs/api-reference/upset_data.md This snippet demonstrates the basic usage of `upset_data()` with default parameters. It processes a sample dataframe and returns the processed data, which can then be used for plotting. ```r library(ComplexUpset) # Create sample binary data data <- data.frame( A = c(1, 1, 0, 1, 0), B = c(1, 0, 1, 1, 0), C = c(0, 1, 1, 0, 1), value = c(10, 20, 15, 25, 30) ) # Process data with defaults processed <- upset_data(data, intersect = c('A', 'B', 'C')) # Access processed data head(processed$matrix_frame) # Intersection membership in long format processed$sorted$groups # Sorted set names processed$plot_intersections_subset # Which intersections to display ``` -------------------------------- ### Bar Geometry and Text Labels Source: https://github.com/krassowski/complex-upset/blob/master/vignettes/Examples.ipynb Configures bar geometry for counts and fills, and adds text labels with percentage formatting and conditional coloring based on MPAA rating. Use this for detailed proportion visualization. ```R geom_bar(stat='count', position='fill', na.rm=TRUE), geom_text( aes( label=!!aes_percentage(relative_to='intersection'), color=ifelse(mpaa == 'R', 'show', 'hide') ), stat='count', position=position_fill(vjust = .5) ), scale_y_continuous(labels=scales::percent_format()), show_hide_scale, rating_scale ) ) ) ) ``` ```