### Run Examples from Repository Source: https://github.com/edmundmiller/altair-upset/blob/main/README.md Clone the repository, install dependencies, and run Python example scripts to explore features. ```bash git clone https://github.com/edmundmiller/altair-upset.git cd altair-upset pip install -e ".[examples]" python examples/basic_upset.py ``` -------------------------------- ### Install altair-upset Source: https://context7.com/edmundmiller/altair-upset/llms.txt Install the library using pip or conda. ```bash pip install altair-upset # or conda install -c conda-forge altair-upset ``` -------------------------------- ### Clone Repository and Install Development Dependencies Source: https://github.com/edmundmiller/altair-upset/blob/main/README.md Clone the Altair UpSet repository and install development, testing, and documentation dependencies in a virtual environment. ```bash git clone https://github.com/edmundmiller/altair-upset.git cd altair-upset python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate pip install -e ".[dev,test,docs]" ``` -------------------------------- ### Install Pre-commit Hooks Source: https://github.com/edmundmiller/altair-upset/blob/main/README.md Install pre-commit hooks to ensure code quality and consistency before committing changes. ```bash pre-commit install ``` -------------------------------- ### Install altair-upset with conda Source: https://github.com/edmundmiller/altair-upset/blob/main/README.md Use this command to install the library using conda. ```bash conda install -c conda-forge altair-upset ``` -------------------------------- ### Install altair-upset Source: https://github.com/edmundmiller/altair-upset/blob/main/docs/index.md Install the library using pip. For conda users, refer to the commented-out section in the source. ```bash pip install altair-upset ``` -------------------------------- ### Create an UpSet Plot with Pandas Source: https://github.com/edmundmiller/altair-upset/blob/main/docs/index.md Demonstrates how to create a basic UpSet plot using a Pandas DataFrame. Ensure you have pandas and altair-upset installed. ```python import altair_upset as au import pandas as pd # Using Pandas data = pd.DataFrame({ 'set1': [1, 0, 1, 1], 'set2': [1, 1, 0, 1], 'set3': [0, 1, 1, 0] }) # Create an UpSet plot chart = au.UpSetAltair( data=data, sets=["set1", "set2", "set3"], title="Sample UpSet Plot" ).chart chart ``` -------------------------------- ### UpSetChart Wrapper Object Methods Source: https://context7.com/edmundmiller/altair-upset/llms.txt The `UpSetChart` instance returned by `UpSetAltair` and `UpSetVertical` provides methods for chart manipulation and export. Use `properties()` for fluent updates, `configure_axis()` for axis styling, and `to_dict()` to get the Vega-Lite JSON specification. The `save()` method exports the chart to various formats. ```python import altair_upset as au import pandas as pd data = pd.DataFrame({ "Set A": [1, 0, 1, 1], "Set B": [1, 1, 0, 1], "Set C": [0, 1, 1, 0], }) upset = au.UpSetAltair(data=data, sets=["Set A", "Set B", "Set C"]) # Fluent property update (returns self) upset = upset.properties(title={"text": "Retitled Chart"}) # Configure axis styling upset = upset.configure_axis(labelFontSize=12) # Get the raw Vega-Lite JSON spec (for embedding in web apps) import json spec = upset.to_dict() print(json.dumps(spec, indent=2)[:300]) # first 300 chars # Save as HTML, PNG, SVG, or Vega-Lite JSON upset.save("output.html") upset.save("output.png") # requires vl-convert-python upset.save("output.json") # Access the underlying altair chart raw_chart = upset.chart ``` -------------------------------- ### Create UpSet Plot with Custom Colors Source: https://github.com/edmundmiller/altair-upset/blob/main/docs.md Example of creating an UpSet plot with custom color ranges for sets and a specific highlight color. ```python chart = au.UpSetAltair( data=data, title="Custom Colored UpSet Plot", sets=["set1", "set2", "set3"], color_range=["#1f77b4", "#ff7f0e", "#2ca02c"], highlight_color="#d62728" ) ``` -------------------------------- ### Create UpSet Plot with Abbreviations Source: https://github.com/edmundmiller/altair-upset/blob/main/docs.md Example of using abbreviations for set names in an UpSet plot. This can make the plot more concise when set names are long. ```python chart = au.UpSetAltair( data=data, title="UpSet Plot with Abbreviations", sets=["set1", "set2", "set3"], abbre=["S1", "S2", "S3"] ) ``` -------------------------------- ### Generate Gene Pathway Data and UpSet Plot Source: https://context7.com/edmundmiller/altair-upset/llms.txt This code generates synthetic gene-pathway membership data and then uses Altair-Upset to create an UpSet plot visualizing the intersections between pathways. It also prints a summary of unique genes per pathway. Ensure pandas, numpy, and altair-upset are installed. ```python import altair_upset as au import pandas as pd import numpy as np np.random.seed(42) n_genes = 2000 pathways = { "Cell_Cycle": 0.15, "DNA_Repair": 0.10, "Apoptosis": 0.12, "Immune_Response": 0.20, "Metabolism": 0.25, "Signal_Transduction": 0.30, } data = pd.DataFrame() for pathway, prob in pathways.items(): if pathway == "Cell_Cycle": data[pathway] = np.random.choice([0, 1], n_genes, p=[1 - prob, prob]) elif pathway == "DNA_Repair": p = np.where(data["Cell_Cycle"] == 1, 0.30, 0.05) data[pathway] = np.random.binomial(1, np.clip(p, 0, 1)) elif pathway == "Apoptosis": p = 0.05 + 0.15 * data["Cell_Cycle"] + 0.1 * data["DNA_Repair"] data[pathway] = np.random.binomial(1, np.clip(p, 0, 1)) else: data[pathway] = np.random.choice([0, 1], n_genes, p=[1 - prob, prob]) chart = au.UpSetAltair( data=data, sets=list(pathways.keys()), title="Gene Set Pathway Intersections", subtitle=f"{n_genes} genes across 6 biological pathways", sort_by="frequency", sort_order="descending", width=1100, height=620, glyph_size=100, line_connection_size=2, highlight="greatest", # pin highlight to largest intersection ) chart.save("gene_pathways.html") # Quick text summary of unique genes per pathway for pathway in pathways: others = [p for p in pathways if p != pathway] unique = data[(data[pathway] == 1) & (data[others].sum(axis=1) == 0)] print(f"{pathway}: {len(unique)} unique genes ({len(unique)/n_genes*100:.1f}%)") ``` -------------------------------- ### Import Libraries and Create Sample Data Source: https://github.com/edmundmiller/altair-upset/blob/main/docs/examples/basic_upset.md Imports pandas, numpy, and altair_upset. Creates a sample DataFrame representing user subscriptions to various streaming services with realistic patterns. ```python import altair_upset as au import pandas as pd import numpy as np # Create sample data with realistic subscription patterns np.random.seed(42) n_users = 1000 # Generate binary data for each service services = ['Netflix', 'Prime', 'Disney+', 'Hulu', 'AppleTV+'] probabilities = [0.7, 0.6, 0.4, 0.3, 0.2] # Probability of subscription for each service data = pd.DataFrame() for service, prob in zip(services, probabilities): data[service] = np.random.choice([0, 1], size=n_users, p=[1-prob, prob]) ``` -------------------------------- ### Import Libraries and Create Sample Data Source: https://github.com/edmundmiller/altair-upset/blob/main/docs/examples/advanced_features.md Imports necessary libraries (altair_upset, pandas, numpy) and generates sample user data with platform usage and engagement metrics. ```python import altair_upset as au import pandas as pd import numpy as np # Create sample data with metrics np.random.seed(42) n_users = 1000 # Generate platform usage data with engagement metrics platforms = ['Facebook', 'Instagram', 'Twitter', 'LinkedIn', 'TikTok'] data = pd.DataFrame({ platform: np.random.choice([0, 1], size=n_users, p=[0.3, 0.7]) for platform in platforms }) # Add engagement metrics data['daily_time_spent'] = np.random.lognormal(3, 1, n_users) # minutes data['posts_per_week'] = np.random.poisson(5, n_users) data['engagement_rate'] = np.beta(2, 5, n_users) ``` -------------------------------- ### Import Libraries and Create Sample Data Source: https://github.com/edmundmiller/altair-upset/blob/main/docs/examples/custom_tooltips.md Imports necessary libraries (altair_upset, pandas, numpy) and generates sample data for social media platform usage, including user demographics and engagement metrics. This data is then processed to calculate metrics for different platform combinations. ```python import altair_upset as au import pandas as pd import numpy as np # Create sample data: Social media platform usage with additional metrics np.random.seed(42) n_users = 1000 # Generate platform usage data platforms = ['Facebook', 'Instagram', 'Twitter', 'LinkedIn', 'TikTok'] data = pd.DataFrame({ platform: np.random.choice([0, 1], size=n_users, p=[0.3, 0.7]) for platform in platforms }) # Add user demographics and engagement metrics data['age'] = np.random.normal(30, 10, n_users).astype(int) data['posts_per_week'] = np.random.poisson(5, n_users) data['engagement_rate'] = np.random.beta(2, 5, n_users) data['account_age_years'] = np.random.uniform(0, 10, n_users).round(1) # Calculate average metrics for each platform combination def calculate_metrics(group): return pd.Series({ 'users': len(group), 'avg_age': group['age'].mean(), 'avg_posts': group['posts_per_week'].mean(), 'avg_engagement': group['engagement_rate'].mean() * 100, # Convert to percentage 'avg_account_age': group['account_age_years'].mean() }) # Get combination metrics combinations = data.groupby(platforms).apply(calculate_metrics).reset_index() ``` -------------------------------- ### UpSetAltair Constructor Parameters Source: https://github.com/edmundmiller/altair-upset/blob/main/docs.md Lists the parameters available for the UpSetAltair constructor, including data, titles, set configurations, sorting options, and visual styling. ```python UpSetAltair( data=None, title="", subtitle="", sets=None, abbre=None, sort_by="frequency", sort_order="ascending", width=1200, height=700, height_ratio=0.6, horizontal_bar_chart_width=300, color_range=["#55A8DB", "#3070B5", "#30363F", "#F1AD60", "#DF6234", "#BDC6CA"], highlight_color="#EA4667", glyph_size=200, set_label_bg_size=1000, line_connection_size=2, horizontal_bar_size=20, vertical_bar_label_size=16, vertical_bar_padding=20, ) ``` -------------------------------- ### Filter Data with Polars for UpSet Plot Source: https://github.com/edmundmiller/altair-upset/blob/main/docs/examples/polars_example.md Utilizes Polars for efficient data filtering before creating an UpSet plot. This example filters for users active on Instagram, TikTok, or Twitter. ```python # Use Polars for fast data filtering active_users = data.filter( pl.col('Instagram') | pl.col('TikTok') | pl.col('Twitter') ).to_pandas() au.UpSetAltair( data=active_users, sets=platforms, title="Active Social Media Users", subtitle="Users with at least one social media account" ).chart ``` -------------------------------- ### Run Tests Source: https://github.com/edmundmiller/altair-upset/blob/main/README.md Execute the test suite using pytest to verify the library's functionality. ```bash pytest ``` -------------------------------- ### Create Sample Polars DataFrame Source: https://github.com/edmundmiller/altair-upset/blob/main/docs/examples/polars_example.md Imports necessary libraries and generates sample data using Polars DataFrames to simulate social media usage patterns. ```python import altair_upset as au import polars as pl import numpy as np # Create sample data with realistic social media usage patterns np.random.seed(42) n_users = 1000 # Generate binary data for each platform platforms = ['Instagram', 'TikTok', 'Twitter', 'LinkedIn', 'Facebook'] probabilities = [0.8, 0.6, 0.5, 0.4, 0.7] # Probability of using each platform # Create data using Polars data_dict = {} for platform, prob in zip(platforms, probabilities): data_dict[platform] = np.random.choice([0, 1], size=n_users, p=[1-prob, prob]) data = pl.DataFrame(data_dict) ``` -------------------------------- ### Import Libraries and Simulate Gene Set Data Source: https://github.com/edmundmiller/altair-upset/blob/main/docs/examples/gene_sets.md Imports necessary libraries and generates simulated gene set data with realistic overlaps between pathways. Sets a random seed for reproducibility. ```python import altair_upset as au import pandas as pd import numpy as np # Simulate gene set data np.random.seed(42) n_genes = 2000 # Define pathways and their approximate sizes pathways = { 'Cell_Cycle': 0.15, # 15% of genes 'DNA_Repair': 0.10, 'Apoptosis': 0.12, 'Immune_Response': 0.20, 'Metabolism': 0.25, 'Signal_Transduction': 0.30 } # Create data with realistic overlaps data = pd.DataFrame() for pathway, prob in pathways.items(): # Add some correlation between related pathways if pathway == 'Cell_Cycle': data[pathway] = np.random.choice([0, 1], size=n_genes, p=[1-prob, prob]) elif pathway == 'DNA_Repair': # DNA repair genes are more likely to be involved in cell cycle p_repair = np.where(data['Cell_Cycle'] == 1, 0.3, 0.05) p_repair = np.clip(p_repair, 0, 1) # Ensure probabilities are valid data[pathway] = np.random.binomial(1, p_repair) elif pathway == 'Apoptosis': # Apoptosis genes might be involved in cell cycle and DNA repair p_apoptosis = 0.05 + 0.15 * data['Cell_Cycle'] + 0.1 * data['DNA_Repair'] p_apoptosis = np.clip(p_apoptosis, 0, 1) # Ensure probabilities are valid data[pathway] = np.random.binomial(1, p_apoptosis) else: data[pathway] = np.random.choice([0, 1], size=n_genes, p=[1-prob, prob]) ``` -------------------------------- ### Create a Basic UpSet Plot Source: https://github.com/edmundmiller/altair-upset/blob/main/docs.md Demonstrates the basic usage of UpSetAltair to create an interactive UpSet plot. Requires pandas for data manipulation. ```python import altair_upset as au import pandas as pd # Create sample data data = pd.DataFrame({ 'set1': [1, 0, 1], 'set2': [1, 1, 0], 'set3': [0, 1, 1] }) # Create UpSet plot chart = au.UpSetAltair( data=data, title="Sample UpSet Plot", sets=["set1", "set2", "set3"] ) # Display the chart chart.show() ``` -------------------------------- ### Analyze Engagement Metrics for Platform Combinations Source: https://github.com/edmundmiller/altair-upset/blob/main/docs/examples/advanced_features.md Calculates and prints average engagement metrics (time spent, posts, engagement rate) for individual platforms and identifies the top 3 most engaged platform combinations. This code is for analysis and does not generate a plot. ```python # Calculate average engagement metrics for each platform for platform in platforms: platform_data = data[data[platform] == 1] print(f"\n{platform} Metrics:") print(f"Users: {len(platform_data)}") print(f"Average daily time: {platform_data['daily_time_spent'].mean():.1f} minutes") print(f"Average posts per week: {platform_data['posts_per_week'].mean():.1f}") print( f"Average engagement rate: {platform_data['engagement_rate'].mean()*100:.1f}%" ) # Find most engaged platform combinations def get_engagement_metrics(group): return pd.Series( { "users": len(group), "avg_time": group["daily_time_spent"].mean(), "avg_posts": group["posts_per_week"].mean(), "avg_engagement": group["engagement_rate"].mean() * 100, } ) # Calculate metrics for all combinations combinations = data.groupby(platforms).apply(get_engagement_metrics).reset_index() # Sort by average engagement top_engaged = combinations.sort_values("avg_engagement", ascending=False).head(3) print("\nTop 3 Most Engaged Platform Combinations:") for _, row in top_engaged.iterrows(): active_platforms = [p for p, v in zip(platforms, row[platforms]) if v == 1] print(f"\n{' & '.join(active_platforms)}:") print(f"Users: {row['users']}") print(f"Avg Time: {row['avg_time']:.1f} minutes") print(f"Avg Posts: {row['avg_posts']:.1f} per week") print(f"Avg Engagement: {row['avg_engagement']:.1f}%") ``` -------------------------------- ### Create Basic UpSet Plot Source: https://github.com/edmundmiller/altair-upset/blob/main/docs/examples/basic_upset.md Generates a simple UpSet plot with default settings using the created data and service list. ```python au.UpSetAltair( data=data, sets=services, title="Streaming Service Subscriptions", subtitle="Distribution of user subscriptions across streaming platforms" ).chart ``` -------------------------------- ### Programmatic intersection highlighting with highlight parameter Source: https://context7.com/edmundmiller/altair-upset/llms.txt The `highlight` parameter in both `UpSetAltair` and `UpSetVertical` allows programmatic highlighting of intersections. It accepts keywords like 'least' or 'greatest', or a 0-based integer index or a list of indices. ```python import altair_upset as au import pandas as pd import numpy as np np.random.seed(7) platforms = ["Facebook", "Instagram", "Twitter", "LinkedIn", "TikTok"] data = pd.DataFrame({ p: np.random.choice([0, 1], size=800, p=[0.35, 0.65]) for p in platforms }) # Highlight the single largest intersection au.UpSetAltair(data=data, sets=platforms, title="Largest intersection", highlight="greatest").show() # Highlight the single smallest intersection au.UpSetAltair(data=data, sets=platforms, title="Smallest intersection", highlight="least").show() # Highlight by 0-based index au.UpSetAltair(data=data, sets=platforms, title="Index 2 highlighted", highlight=2).show() ``` -------------------------------- ### Create Basic UpSet Plot with Metrics Source: https://github.com/edmundmiller/altair-upset/blob/main/docs/examples/advanced_features.md Generates a basic UpSet plot visualizing social media platform usage and user engagement patterns. Requires the altair_upset library and pandas DataFrame. ```python au.UpSetAltair( data=data, sets=platforms, title="Social Media Platform Usage Analysis", subtitle="Interactive analysis of user engagement patterns", width=800, height=500 ).chart ``` -------------------------------- ### Low-Level Chart Styling with `upsetaltair_top_level_configuration` Source: https://context7.com/edmundmiller/altair-upset/llms.txt The `upsetaltair_top_level_configuration` helper applies common styling to Altair charts, such as axis fonts, legend appearance, and view stroke. It is useful for creating custom UpSet-style charts from scratch using Altair components. ```python from altair_upset import upsetaltair_top_level_configuration import altair as alt import pandas as pd # Assume `my_chart` is a manually composed alt.VConcatChart data = pd.DataFrame({"x": [1, 2, 3], "y": [4, 5, 6]}) my_chart = alt.Chart(data).mark_bar().encode( x="x:Q", y="y:Q" ) styled = upsetaltair_top_level_configuration( my_chart, legend_orient="top-left", # Altair legend orient string legend_symbol_size=250, # area in px² of legend symbols ) styled.show() ``` -------------------------------- ### Apply Altair Themes Source: https://context7.com/edmundmiller/altair-upset/llms.txt Apply registered Altair themes to the UpSet chart by passing the theme name to the `theme` parameter. The theme is enabled globally using `alt.themes.enable()` before chart construction. ```python import altair as alt import altair_upset as au import pandas as pd import numpy as np np.random.seed(1) sets = ["A", "B", "C", "D"] data = pd.DataFrame({s: np.random.randint(0, 2, 200) for s in sets}) # Built-in Altair themes: "default", "dark", "fivethirtyeight", "ggplot2", "latimes", # "quartz", "urbaninstitute", "vox" for theme_name in ["dark", "ggplot2"]: chart = au.UpSetAltair( data=data, sets=sets, title=f"Theme: {theme_name}", theme=theme_name, width=700, height=430, ) chart.save(f"upset_{theme_name}.html") ``` -------------------------------- ### Basic UpSet Plot with Pandas Source: https://github.com/edmundmiller/altair-upset/blob/main/README.md Create a basic UpSet plot using Pandas DataFrames. Ensure Altair and Pandas are imported. ```python import altair_upset as au import pandas as pd # Create sample data with Pandas data = pd.DataFrame({ 'set1': [1, 0, 1, 1], 'set2': [1, 1, 0, 1], 'set3': [0, 1, 1, 0] }) # Create UpSet plot chart = au.UpSetAltair( data=data, # or data_pl.to_pandas() sets=["set1", "set2", "set3"], title="Sample UpSet Plot" ) # Display the chart chart.show() ``` -------------------------------- ### Analyze Platform-Specific Statistics Source: https://github.com/edmundmiller/altair-upset/blob/main/docs/examples/custom_tooltips.md Calculates and prints platform-specific metrics such as the number of users, average age, average posts per week, average engagement rate, and average account age for each social media platform. This provides a detailed breakdown of user behavior on individual platforms. ```python # Platform-specific statistics print("Platform-specific metrics:") for platform in platforms: platform_users = data[data[platform] == 1] metrics = { "Users": len(platform_users), "Avg Age": platform_users["age"].mean(), "Avg Posts/Week": platform_users["posts_per_week"].mean(), "Avg Engagement": platform_users["engagement_rate"].mean() * 100, "Avg Account Age": platform_users["account_age_years"].mean(), } print(f" {platform}:") for metric, value in metrics.items(): print(f"- {metric}: {value:.1f}") ``` -------------------------------- ### Identify Most Engaged Combinations Source: https://github.com/edmundmiller/altair-upset/blob/main/docs/examples/custom_tooltips.md Identifies and prints the top 3 most engaged platform combinations based on the calculated average engagement rate. It details the active platforms, number of users, average engagement rate, average posts per week, and average user age for these top combinations. ```python # Most engaged combinations print("\nTop 3 most engaged platform combinations:") engagement_by_combination = combinations.sort_values( "avg_engagement", ascending=False ).head(3) for _, row in engagement_by_combination.iterrows(): active_platforms = [p for p, v in zip(platforms, row[platforms]) if v == 1] platform_str = " & ".join(active_platforms) print(f" {platform_str}:") print(f"- Users: {row['users']}") print(f"- Avg Engagement Rate: {row['avg_engagement']:.1f}%") print(f"- Avg Posts per Week: {row['avg_posts']:.1f}") print(f"- Avg User Age: {row['avg_age']:.1f}") ``` -------------------------------- ### highlight parameter Source: https://context7.com/edmundmiller/altair-upset/llms.txt Programmatically pins the highlight color to specific intersections instead of using mouse hover. Accepts 'least', 'greatest', a 0-based integer index, or a list of indices. ```APIDOC ## highlight parameter — Programmatic intersection highlighting ### Description The `highlight` parameter of both `UpSetAltair` and `UpSetVertical` pins the highlight color to one or more intersections instead of responding to mouse hover. Accepts `"least"`, `"greatest"`, a 0-based integer index, or a list of indices. Out-of-bounds indices raise `IndexError` / `ValueError`. ### Parameters - **highlight** (str | int | list[int]) - Required - Specifies which intersection(s) to highlight. Can be `"least"`, `"greatest"`, a single integer index, or a list of integer indices. ### Request Example ```python import altair_upset as au import pandas as pd import numpy as np np.random.seed(7) platforms = ["Facebook", "Instagram", "Twitter", "LinkedIn", "TikTok"] data = pd.DataFrame({ p: np.random.choice([0, 1], size=800, p=[0.35, 0.65]) for p in platforms }) # Highlight the single largest intersection au.UpSetAltair(data=data, sets=platforms, title="Largest intersection", highlight="greatest").show() # Highlight the single smallest intersection au.UpSetAltair(data=data, sets=platforms, title="Smallest intersection", highlight="least").show() # Highlight by 0-based index au.UpSetAltair(data=data, sets=platforms, title="Index 2 highlighted", highlight=2).show() ``` ### Response - **UpSetChart** - An object wrapping an Altair chart with methods for display and saving. ``` -------------------------------- ### Use Abbreviations for Set Names Source: https://context7.com/edmundmiller/altair-upset/llms.txt Use the `abbre` parameter to provide short labels for long set names. These abbreviations are displayed in the matrix dots, while full names appear in the legend. The `abbre` list must have the same length as the `sets` list. ```python import altair_upset as au import pandas as pd data = pd.DataFrame({ "Very Long Name Alpha": [1, 0, 1, 1, 0], "Very Long Name Beta": [1, 1, 0, 1, 0], "Very Long Name Gamma": [0, 1, 1, 0, 1], "Very Long Name Delta": [1, 0, 0, 1, 1], }) chart = au.UpSetAltair( data=data, sets=list(data.columns), abbre=["A", "B", "G", "D"], # shown in matrix circles title="Abbreviated Set Labels", width=700, height=450, ) chart.show() ``` -------------------------------- ### Create Sorted UpSet Plot Source: https://github.com/edmundmiller/altair-upset/blob/main/docs/examples/basic_upset.md Generates an UpSet plot sorted by the frequency of subscription combinations in descending order. ```python au.UpSetAltair( data=data, sets=services, sort_by="frequency", sort_order="descending", title="Most Common Streaming Service Combinations", subtitle="Sorted by number of subscribers" ).chart ``` -------------------------------- ### Create Basic UpSet Plot Source: https://github.com/edmundmiller/altair-upset/blob/main/docs/examples/gene_sets.md Generates a basic UpSet plot visualizing all pathway intersections, sorted by frequency in descending order. Useful for an overview of gene set overlaps. ```python au.UpSetAltair( data=data, sets=data.columns.tolist(), sort_by="frequency", sort_order="descending", title="Gene Set Intersections", subtitle="Distribution of genes across pathways", glyph_size=100, # Ensure positive size set_label_bg_size=500, # Ensure positive size line_connection_size=2, ).chart ``` -------------------------------- ### UpSetAltair Constructor Source: https://github.com/edmundmiller/altair-upset/blob/main/docs.md The UpSetAltair class constructor allows for the creation of interactive UpSet plots. It accepts various parameters to customize the plot's appearance, data, and sorting behavior. ```APIDOC ## UpSetAltair ```python UpSetAltair( data=None, title="", subtitle="", sets=None, abbre=None, sort_by="frequency", sort_order="ascending", width=1200, height=700, height_ratio=0.6, horizontal_bar_chart_width=300, color_range=["#55A8DB", "#3070B5", "#30363F", "#F1AD60", "#DF6234", "#BDC6CA"], highlight_color="#EA4667", glyph_size=200, set_label_bg_size=1000, line_connection_size=2, horizontal_bar_size=20, vertical_bar_label_size=16, vertical_bar_padding=20, ) ``` ### Parameters - **data** : pandas.DataFrame - Input data where each column represents a set and contains binary values (0 or 1) - Required parameter - **title** : str, default "" - Title of the plot - **subtitle** : str or list of str, default "" - Subtitle(s) of the plot - **sets** : list of str - Names of the sets to visualize - Must correspond to column names in the data - Required parameter - **abbre** : list of str, default None - Abbreviations for set names - Must have same length as sets if provided - If None, uses full set names - **sort_by** : {"frequency", "degree"}, default "frequency" - Method to sort the intersections - "frequency": sort by intersection size - "degree": sort by number of sets in intersection - **sort_order** : {"ascending", "descending"}, default "ascending" - Order of sorting for intersections - **width** : int, default 1200 - Total width of the plot in pixels - **height** : int, default 700 - Total height of the plot in pixels - **height_ratio** : float, default 0.6 - Ratio of vertical bar chart height to total height - Must be between 0 and 1 - **horizontal_bar_chart_width** : int, default 300 - Width of the horizontal bar chart in pixels - **color_range** : list of str, default ["#55A8DB", "#3070B5", "#30363F", "#F1AD60", "#DF6234", "#BDC6CA"] - List of colors for the sets - **highlight_color** : str, default "#EA4667" - Color used for highlighting on hover - **glyph_size** : int, default 200 - Size of the matrix glyphs in pixels - **set_label_bg_size** : int, default 1000 - Size of the set label background circles - **line_connection_size** : int, default 2 - Thickness of connecting lines in pixels - **horizontal_bar_size** : int, default 20 - Height of horizontal bars in pixels - **vertical_bar_label_size** : int, default 16 - Font size of vertical bar labels - **vertical_bar_padding** : int, default 20 - Padding between vertical bars ``` -------------------------------- ### Highlight Multiple Intersections Source: https://context7.com/edmundmiller/altair-upset/llms.txt Highlight specific intersections by passing a list of indices to the `highlight` parameter. Ensure indices are within the valid range of intersections. ```python au.UpSetAltair(data=data, sets=platforms, title="Indices 0, 1, 3 highlighted", highlight=[0, 1, 3]).show() ``` ```python try: au.UpSetAltair(data=data, sets=platforms, highlight=999) except IndexError as e: print(e) # "highlight index 999 is out of bounds for N intersections" ``` -------------------------------- ### Generate Enhanced UpSet Plot Source: https://github.com/edmundmiller/altair-upset/blob/main/docs/examples/custom_tooltips.md Creates an UpSet plot using altair_upset with specified data, sets, title, subtitle, and dimensions. This is the primary visualization step for analyzing platform usage patterns. ```python au.UpSetAltair( data=data[platforms], sets=platforms, title="Social Media Platform Usage Patterns", subtitle="Analysis of user behavior across platforms", width=800, height=500 ).chart ``` -------------------------------- ### Horizontal vs. Vertical Orientation Comparison Source: https://github.com/edmundmiller/altair-upset/blob/main/docs/examples/advanced_features.md Compare the same data displayed in both horizontal and vertical orientations. Horizontal is default and best for static figures, while vertical is better for interactive plots. ```python # Horizontal orientation (default) au.UpSetAltair( data=data, sets=platforms, title="Horizontal Layout", subtitle="Cardinality vertical (top), set sizes horizontal (right)", orientation="horizontal", width=800, height=500 ).chart ``` ```python # Vertical orientation au.UpSetAltair( data=data, sets=platforms, title="Vertical Layout", subtitle="Cardinality horizontal (left), set sizes vertical (top)", orientation="vertical", width=600, height=800 ).chart ``` -------------------------------- ### Analyze Age Group Distribution Source: https://github.com/edmundmiller/altair-upset/blob/main/docs/examples/custom_tooltips.md Analyzes and prints the age group distribution for users on each social media platform. It categorizes users into predefined age groups and calculates the normalized frequency of each group per platform, providing insights into the demographic composition of platform users. ```python # Age distribution analysis print("\nAge group distribution across platforms:") data["age_group"] = pd.cut( data["age"], bins=[0, 20, 30, 40, 50, 100], labels=["<20", "20-30", "30-40", "40-50", "50+"], ) for platform in platforms: print(f" {platform} age distribution:") age_dist = ( data[data[platform] == 1]["age_group"].value_counts(normalize=True).sort_index() ) for age_group, percentage in age_dist.items(): print(f"- {age_group}: {percentage*100:.1f}%") ``` -------------------------------- ### Create Styled UpSet Plot Source: https://github.com/edmundmiller/altair-upset/blob/main/docs/examples/basic_upset.md Generates an UpSet plot with custom styling, including brand colors, a highlight color, and specified dimensions. ```python au.UpSetAltair( data=data, sets=services, title="Streaming Service Subscriptions (Styled)", subtitle="With custom colors and styling", color_range=["#E50914", "#00A8E1", "#113CCF", "#1CE783", "#000000"], # Brand colors highlight_color="#FFD700", width=800, height=500 ).chart ``` -------------------------------- ### Generate Basic UpSet Plot with Polars Data Source: https://github.com/edmundmiller/altair-upset/blob/main/docs/examples/polars_example.md Creates a basic UpSet plot by converting a Polars DataFrame to pandas. The UpSetAltair function handles the visualization. ```python # Convert Polars DataFrame to pandas for visualization pandas_df = data.to_pandas() au.UpSetAltair( data=pandas_df, sets=platforms, title="Social Media Platform Usage", subtitle="Distribution of user activity across social media platforms" ).chart ``` -------------------------------- ### Create UpSet Plot Sorted by Degree Source: https://github.com/edmundmiller/altair-upset/blob/main/docs.md Demonstrates how to sort the intersections in an UpSet plot by their degree (number of sets) in descending order. ```python chart = au.UpSetAltair( data=data, title="UpSet Plot Sorted by Degree", sets=["set1", "set2", "set3"], sort_by="degree", sort_order="descending" ) ``` -------------------------------- ### Highlight Multiple Intersections by Index Source: https://github.com/edmundmiller/altair-upset/blob/main/docs/examples/advanced_features.md Generates an UpSet plot highlighting multiple specific intersections using a list of their 0-based indices. Enables simultaneous focus on several data subsets. ```python # Highlight the first three intersections au.UpSetAltair( data=data, sets=platforms, title="Social Media Platform Usage - Multiple Intersections Highlighted", highlight=[0, 1, 2], width=800, height=500 ).chart ``` -------------------------------- ### Generate UpSet Plot with Altair Source: https://github.com/edmundmiller/altair-upset/blob/main/docs/api.md Use this function to create interactive UpSet plots. It requires pandas DataFrames for input and a list of set names. Customize appearance with various parameters like title, colors, and sorting. ```python >>> import altair_upset as au >>> import pandas as pd >>> data = pd.DataFrame({ ... 'set1': [1, 0, 1], ... 'set2': [1, 1, 0], ... 'set3': [0, 1, 1] ... }) >>> chart = au.UpSetAltair( ... data=data, ... sets=["set1", "set2", "set3"], ... title="Sample UpSet Plot" ... ) ``` -------------------------------- ### Create a vertical UpSet plot with UpSetVertical Source: https://context7.com/edmundmiller/altair-upset/llms.txt Use UpSetVertical to create a vertical UpSet plot, which is ideal for interactive dashboards with vertical scrolling. It shares the same parameter surface as UpSetAltair but offers a rotated layout. ```python import altair_upset as au import pandas as pd import numpy as np np.random.seed(0) platforms = ["Facebook", "Instagram", "Twitter", "LinkedIn", "TikTok"] data = pd.DataFrame({ p: np.random.choice([0, 1], size=500, p=[0.3, 0.7]) for p in platforms }) chart = au.UpSetVertical( data=data, sets=platforms, title="Social Media Platform Usage (Vertical)", subtitle="Better for scrollable interactive exploration", sort_by="frequency", sort_order="descending", width=700, height=900, height_ratio=0.4, # fraction of height for set-size bars cardinality_bar_width=160, # explicit width for cardinality bar panel cardinality_bar_x_axis_orient="bottom", # "top" | "bottom" highlight_color="#EA4667", ) chart.show() chart.save("upset_social_vertical.html") ``` -------------------------------- ### Create UpSet Plot for Tennis Grand Slam Champions Source: https://github.com/edmundmiller/altair-upset/blob/main/docs/examples/tennis_grand_slam.md Generates an UpSet plot visualization using the prepared data. Customize plot appearance with parameters like sorting, title, subtitle, and dimensions. ```python au.UpSetAltair( data=data, sets=data.columns.tolist(), sort_by="degree", sort_order="descending", title="Tennis Grand Slam Championships by Player", subtitle=[ "This plot shows the overlap of tennis Grand Slam tournament winners.", "Notably, the majority of champions have won only at one tournament venue.", "Out of 117 champions, only 9 have won at least once at every Grand Slam tournament venue." ], width=800, height=500 ).chart ``` -------------------------------- ### Polars DataFrame Integration for Preprocessing Source: https://context7.com/edmundmiller/altair-upset/llms.txt Altair-Upset functions accept only Pandas DataFrames. Use Polars for efficient data preprocessing, then convert the Polars DataFrame to Pandas using `.to_pandas()` before passing it to `UpSetAltair` or `UpSetVertical`. ```python import altair_upset as au import polars as pl import numpy as np np.random.seed(42) platforms = ["Instagram", "TikTok", "Twitter", "LinkedIn", "Facebook"] probs = [0.8, 0.6, 0.5, 0.4, 0.7] data_pl = pl.DataFrame({ p: np.random.choice([0, 1], size=2000, p=[1 - prob, prob]) for p, prob in zip(platforms, probs) }) # Use Polars for fast filtering before plotting active = data_pl.filter( pl.col("Instagram") | pl.col("TikTok") | pl.col("Twitter") ) chart = au.UpSetAltair( data=active.to_pandas(), # convert at the boundary sets=platforms, title="Active Social Media Users", subtitle="Users active on at least one of Instagram, TikTok, or Twitter", sort_by="frequency", sort_order="descending", width=850, height=520, ) chart.show() ``` -------------------------------- ### Highlight Smallest Intersection in UpSet Plot Source: https://github.com/edmundmiller/altair-upset/blob/main/docs/examples/advanced_features.md Generates an UpSet plot that programmatically highlights the intersection with the least number of users. Useful for drawing attention to less common user group patterns. ```python au.UpSetAltair( data=data, sets=platforms, title="Social Media Platform Usage - Smallest Intersection Highlighted", highlight="least", width=800, height=500 ).chart ``` -------------------------------- ### Use Abbreviations for Set Names Source: https://github.com/edmundmiller/altair-upset/blob/main/README.md Provide abbreviations for long set names to improve readability in the UpSet plot. ```python # Use abbreviations for long set names chart = au.UpSetAltair( data=data, sets=["Very Long Set Name 1", "Very Long Set Name 2", "Very Long Set Name 3"], abbre=["S1", "S2", "S3"] ) ```