### Install pyCirclize with Tooltip Support Source: https://github.com/moshi4/pycirclize/blob/main/README.md Instructions for installing pyCirclize with the necessary dependencies for tooltip functionality. This can be done using pip or conda. Interactive plots require a live Python kernel. ```shell pip install pycirclize[tooltip] ``` ```shell conda install -c conda-forge pycirclize ipympl ``` -------------------------------- ### Load Prokaryote Example Genomes using PyCirclize Source: https://github.com/moshi4/pycirclize/blob/main/docs/circos_plot.ipynb Demonstrates how to load example prokaryotic genome files, either in GFF or Genbank format, using the `pycirclize.utils.load_prokaryote_example_file` function. It shows the initialization of a parser object, either `Gff` or `Genbank`, based on the loaded file. This is a prerequisite for further visualization steps. ```python from pycirclize.parser import Gff, Genbank from pycirclize.utils import load_prokaryote_example_file # Case1. Load `GFF` contig genomes # https://github.com/moshi4/pycirclize-data/blob/main/prokaryote/mycoplasma_alvi.gff gff_file = load_prokaryote_example_file("mycoplasma_alvi.gff") parser_gff = Gff(gff_file) # Case2. Load `Genbank` contig genomes # https://github.com/moshi4/pycirclize-data/blob/main/prokaryote/mycoplasma_alvi.gbk gbk_file = load_prokaryote_example_file("mycoplasma_alvi.gbk") parser_gbk = Genbank(gbk_file) ``` -------------------------------- ### Install pycirclize Package Source: https://github.com/moshi4/pycirclize/blob/main/docs/circos_plot.ipynb This snippet shows the command to install the pycirclize library using pip. This is a prerequisite for running the subsequent code examples. ```python # %pip install pycirclize ``` -------------------------------- ### Plot Chord Diagram from 10x10 Matrix Data with pyCirclize Source: https://github.com/moshi4/pycirclize/blob/main/docs/chord_diagram.ipynb Creates a Chord Diagram from a randomly generated 10x10 matrix using pyCirclize. This example demonstrates plotting with a larger dataset and custom tick intervals for better readability. The input is a Pandas DataFrame. ```python from pycirclize import Circos import pandas as pd # Create matrix data (10 x 10) row_names = list("ABCDEFGHIJ") col_names = row_names matrix_data = [ [51, 115, 60, 17, 120, 126, 115, 179, 127, 114], [108, 138, 165, 170, 85, 221, 75, 107, 203, 79], [108, 54, 72, 123, 84, 117, 106, 114, 50, 27], [62, 134, 28, 185, 199, 179, 74, 94, 116, 108], [211, 114, 49, 55, 202, 97, 10, 52, 99, 111], [87, 6, 101, 117, 124, 171, 110, 14, 175, 164], [167, 99, 109, 143, 98, 42, 95, 163, 134, 78], [88, 83, 136, 71, 122, 20, 38, 264, 225, 115], [145, 82, 87, 123, 121, 55, 80, 32, 50, 12], [122, 109, 84, 94, 133, 75, 71, 115, 60, 210], ] matrix_df = pd.DataFrame(matrix_data, index=row_names, columns=col_names) # Initialize Circos instance for chord diagram plot circos = Circos.chord_diagram( matrix_df, space=3, r_lim=(93, 100), cmap="tab10", ticks_interval=500, label_kws=dict(r=94, size=12, color="white"), ) print(matrix_df) fig = circos.plotfig() ``` -------------------------------- ### Dataset Loading Functions Source: https://github.com/moshi4/pycirclize/blob/main/docs/api-docs/utils.md This section details the functions available for loading example datasets and files for prokaryotic and eukaryotic data, as well as tree files and image files. ```APIDOC ## Dataset Loading Utility Functions ### Description These functions are designed to load example datasets and files commonly used with the pycirclize library, including data for prokaryotes, eukaryotes, tree structures, and images. ### Endpoint `/moshi4/pycirclize/utils/dataset` ### Functions #### `load_prokaryote_example_file()` * **Description**: Loads an example file for prokaryotic data. * **Method**: Not Applicable (Function) #### `load_eukaryote_example_dataset()` * **Description**: Loads an example dataset for eukaryotic data. * **Method**: Not Applicable (Function) #### `load_example_tree_file()` * **Description**: Loads an example tree file. * **Method**: Not Applicable (Function) #### `load_example_image_file()` * **Description**: Loads an example image file. * **Method**: Not Applicable (Function) #### `fetch_genbank_by_accid(accession_id: str)` * **Description**: Fetches GenBank data using an accession ID. * **Method**: Not Applicable (Function) * **Parameters**: * `accession_id` (str) - Required - The GenBank accession ID. ``` -------------------------------- ### Plotting Colorbars with pyCirclize Source: https://github.com/moshi4/pycirclize/blob/main/docs/plot_tips.ipynb This example demonstrates how to plot colorbars using the `circos.colorbar()` method in pyCirclize. It shows how to create heatmap tracks with different colormaps and then add colorbars associated with these heatmaps, including options for positioning, orientation, and labeling. ```python from pycirclize import Circos import numpy as np np.random.seed(0) # Initialize Circos instance circos = Circos(sectors=dict(data=100), start=90) sector = circos.sectors[0] # Plot heatmap track1 (cmap="bwr") track1 = sector.add_track((85, 100)) track1.axis() vmin1, vmax1, cmap1 = 0, 100, "bwr" matrix1 = np.random.randint(vmin1, vmax1, (5, 100)) track1.heatmap(matrix1, cmap=cmap1, vmin=vmin1, vmax=vmax1) # Plot heatmap track2 (cmap="viridis") track2 = sector.add_track((65, 80)) track2.axis() vmin2, vmax2, cmap2 = -200, 200, "viridis" matrix2 = np.random.randint(vmin2, vmax2, (3, 100)) track2.heatmap(matrix2, cmap=cmap2, vmin=vmin2, vmax=vmax2) # Plot colorbar in various style # bounds = (x, y, width, height) circos.colorbar(vmin=vmin1, vmax=vmax1) circos.colorbar(bounds=(0.7, 0.6, 0.02, 0.3), vmin=vmin1, vmax=vmax1, cmap="bwr") circos.colorbar(bounds=(0.8, 0.6, 0.02, 0.3), vmin=vmin2, vmax=vmax2, cmap="viridis") circos.colorbar( bounds=(0.3, 0.485, 0.4, 0.03), vmin=vmin2, vmax=vmax2, cmap="viridis", orientation="horizontal", label="Colorbar in center", label_kws=dict(size=12, color="blue"), tick_kws=dict(labelsize=12, colors="red"), ) fig = circos.plotfig() ``` -------------------------------- ### PyCircos: Plotting Fill Between Areas Source: https://github.com/moshi4/pycirclize/blob/main/docs/plot_api_example.ipynb This example demonstrates using the `fill_between` function in pycirclize to shade areas on a track. It includes examples for simple linear fills and fills based on arrays of random points, with options for edge color and line style. ```python from pycirclize import Circos import numpy as np np.random.seed(0) sectors = {"A": 10, "B": 20, "C": 15} circos = Circos(sectors, space=5) for sector in circos.sectors: vmin, vmax = 0, 10 # Plot fill_between with simple lines track1 = sector.add_track((80, 100), r_pad_ratio=0.1) track1.axis() track1.xticks_by_interval(1) track1.fill_between(x=[track1.start, track1.end], y1=[vmin, vmax], y2=[vmin, vmax / 2]) # Plot fill_between with random points line track2 = sector.add_track((50, 70), r_pad_ratio=0.1) track2.axis() x = np.linspace(track2.start, track2.end, int(track2.size) * 5 + 1) y = np.random.randint(vmin, vmax, len(x)) track2.fill_between(x, y, ec="black", lw=1, ls="dashed") fig = circos.plotfig() ``` -------------------------------- ### Load mm10 Example Dataset (Python) Source: https://github.com/moshi4/pycirclize/blob/main/docs/circos_plot.ipynb This snippet demonstrates loading the mm10 example dataset, which includes chromosome BED file, cytoband file, and chromosome links. This data is typically used with the `pycirclize` library for genomic visualization. The function `load_eukaryote_example_dataset` simplifies data retrieval. ```python from pycirclize import Circos from pycirclize.utils import load_eukaryote_example_dataset import numpy as np np.random.seed(0) # Load mm10 dataset (https://github.com/moshi4/pycirclize-data/tree/main/eukaryote/mm10) chr_bed_file = load_eukaryote_example_dataset("mm10")[0] ``` -------------------------------- ### Create Radar Chart with Markers and Legend using pyCirclize Source: https://github.com/moshi4/pycirclize/blob/main/docs/radar_chart.ipynb Generates a radar chart with customizable markers and a legend. This example demonstrates setting vmax, marker size, circular layout, colormap, and grid interval. It requires pycirclize and pandas. The output is a matplotlib Figure object with a legend. ```python from pycirclize import Circos import pandas as pd # Create RPG jobs parameter dataframe (3 jobs, 7 parameters) df = pd.DataFrame( data=[ [80, 80, 80, 80, 80, 80, 80], [90, 20, 95, 95, 30, 30, 80], [60, 90, 20, 20, 100, 90, 50], ], index=["Hero", "Warrior", "Wizard"], columns=["HP", "MP", "ATK", "DEF", "SP.ATK", "SP.DEF", "SPD"], ) print(df) # Initialize Circos instance for radar chart plot circos = Circos.radar_chart( df, vmax=100, marker_size=6, circular=True, cmap="Set2", grid_interval_ratio=0.25, ) # Plot figure & set legend on upper right fig = circos.plotfig() _ = circos.ax.legend(loc="upper right") ``` -------------------------------- ### PyCircos: Plotting Lines Source: https://github.com/moshi4/pycirclize/blob/main/docs/plot_api_example.ipynb This snippet illustrates how to plot lines on a circos track. It includes examples of plotting a line between two specific points (start and end of the track) and plotting lines based on an array of random values. ```python from pycirclize import Circos import numpy as np np.random.seed(0) sectors = {"A": 10, "B": 20, "C": 15} circos = Circos(sectors, space=5) for sector in circos.sectors: track = sector.add_track((80, 100), r_pad_ratio=0.1) track.axis() track.xticks_by_interval(1) vmin, vmax = 0, 10 # Line between start-end two points track.line([track.start, track.end], [vmin, vmax], lw=1.5, ls="dotted") # Line of random value points x = np.linspace(track.start, track.end, int(track.size) * 5 + 1) y = np.random.randint(vmin, vmax, len(x)) track.line(x, y) fig = circos.plotfig() ``` -------------------------------- ### Plot Chord Diagram from 10x2 Matrix with Custom Link Styling (pyCirclize) Source: https://github.com/moshi4/pycirclize/blob/main/docs/chord_diagram.ipynb Illustrates plotting a Chord Diagram from a 10x2 matrix using pyCirclize, featuring custom link styling. A handler function, `link_kws_handler`, is defined to dynamically set link properties like alpha and zorder for specific rows, allowing for visual highlighting. ```python from pycirclize import Circos from pycirclize.parser import Matrix import pandas as pd # Create matrix data (10 x 2) row_names = list("ABCDEFGHIJ") col_names = list("KL") matrix_data = [ [83, 79], [90, 118], [165, 81], [121, 77], [187, 197], [177, 8], [141, 127], [29, 27], [95, 82], [107, 39], ] matrix_df = pd.DataFrame(matrix_data, index=row_names, columns=col_names) # Define link_kws handler function to customize each link property def link_kws_handler(from_label: str, to_label: str): if from_label in ("C", "G"): # Set alpha, zorder values higher than other links for highlighting return dict(alpha=0.5, zorder=1.0) else: return dict(alpha=0.1, zorder=0) # Initialize Circos instance for chord diagram plot circos = Circos.chord_diagram( matrix_df, space=2, cmap="Set3", label_kws=dict(size=12), link_kws=dict(direction=1, ec="black", lw=0.5), link_kws_handler=link_kws_handler, ) print(matrix_df) fig = circos.plotfig() ``` -------------------------------- ### Create Basic Radar Chart with pyCirclize Source: https://github.com/moshi4/pycirclize/blob/main/docs/radar_chart.ipynb Generates a basic radar chart from a pandas DataFrame. Requires the pycirclize and pandas libraries. The input is a DataFrame where rows represent categories and columns represent parameters. The output is a matplotlib Figure object. ```python # !pip install pycirclize from pycirclize import Circos import pandas as pd # Create RPG jobs parameter dataframe (3 jobs, 6 parameters) df = pd.DataFrame( data=[ [80, 80, 80, 80, 80, 80], [90, 95, 95, 30, 30, 80], [60, 20, 20, 100, 90, 50], ], index=["Hero", "Warrior", "Wizard"], columns=["HP", "ATK", "DEF", "SP.ATK", "SP.DEF", "SPD"], ) print(df) # Initialize Circos instance for radar chart plot circos = Circos.radar_chart(df) # Plot figure fig = circos.plotfig() ``` -------------------------------- ### Create Subplots for Radar Charts with Matplotlib and pyCirclize Source: https://github.com/moshi4/pycirclize/blob/main/docs/radar_chart.ipynb Demonstrates how to create a figure with multiple polar subplots (suitable for radar charts) using matplotlib and pyCirclize. This example sets up a 2x2 grid of polar axes. It requires pycirclize, pandas, and matplotlib. ```python from pycirclize import Circos import pandas as pd import matplotlib.pyplot as plt # Create RPG jobs parameter dataframe (4 jobs, 8 parameters) df = pd.DataFrame( data=[ [80, 80, 80, 80, 80, 80, 80, 80], [90, 20, 95, 95, 30, 30, 80, 70], [60, 90, 20, 20, 100, 90, 50, 70], [70, 50, 60, 40, 60, 40, 100, 60], ], index=["Hero", "Warrior", "Wizard", "Assassin"], columns=["HP", "MP", "ATK", "DEF", "SP.ATK", "SP.DEF", "SPD", "LUK"], ) print(df) # Create 2 x 2 subplots fig = plt.figure(figsize=(16, 16), dpi=100) fig.subplots(2, 2, subplot_kw=dict(polar=True)) fig.subplots_adjust(wspace=0.15, hspace=0.15) ``` -------------------------------- ### Plot Chord Diagram from 3x6 Matrix Data with pyCirclize Source: https://github.com/moshi4/pycirclize/blob/main/docs/chord_diagram.ipynb Generates a Chord Diagram from a 3x6 matrix using pyCirclize. It initializes the Circos object with specified parameters for layout, colormap, and link styling. The input is a Pandas DataFrame representing the matrix. ```python from pycirclize import Circos import pandas as pd # Create matrix dataframe (3 x 6) row_names = ["S1", "S2", "S3"] col_names = ["E1", "E2", "E3", "E4", "E5", "E6"] matrix_data = [ [4, 14, 13, 17, 5, 2], [7, 1, 6, 8, 12, 15], [9, 10, 3, 16, 11, 18], ] matrix_df = pd.DataFrame(matrix_data, index=row_names, columns=col_names) # Initialize Circos instance for chord diagram plot circos = Circos.chord_diagram( matrix_df, start=-265, end=95, space=5, r_lim=(93, 100), cmap="tab10", label_kws=dict(r=94, size=12, color="white"), link_kws=dict(ec="black", lw=0.5), ) print(matrix_df) fig = circos.plotfig() ``` -------------------------------- ### Create Chord Diagram from DataFrame using PyCirclize Source: https://github.com/moshi4/pycirclize/blob/main/docs/chord_diagram.ipynb This snippet shows how to create a chord diagram using pycirclize. It begins by constructing a pandas DataFrame with 'from', 'to', and 'value' columns, which is then parsed into a matrix. Finally, a Circos instance is initialized for the chord diagram with specified styling and plotted. ```python from pycirclize import Circos from pycirclize.parser import Matrix import pandas as pd # Create from-to table dataframe & convert to matrix fromto_table_df = pd.DataFrame( [ ["A", "B", 10], ["A", "C", 5], ["A", "D", 15], ["A", "E", 20], ["A", "F", 3], ["B", "A", 3], ["B", "G", 15], ["F", "D", 13], ["F", "E", 2], ["E", "A", 20], ["E", "D", 6], ], columns=["from", "to", "value"], # Column name is optional ) matrix = Matrix.parse_fromto_table(fromto_table_df) # Initialize Circos instance for chord diagram plot circos = Circos.chord_diagram( matrix, space=3, cmap="viridis", ticks_interval=5, label_kws=dict(size=12, r=110), link_kws=dict(direction=1, ec="black", lw=0.5), ) print(fromto_table_df.to_string(index=False)) fig = circos.plotfig() ``` -------------------------------- ### Visualize Genbank Features with pycirclize Source: https://github.com/moshi4/pycirclize/blob/main/docs/plot_api_example.ipynb This example shows how to visualize genomic features (like CDS) from a Genbank file using pycirclize. It parses the Genbank file, sets up Circos sectors based on sequence IDs, and plots features with different colors for forward and reverse strands. Dependencies include pycirclize and its Genbank parser. ```python from pycirclize import Circos from pycirclize.utils import load_prokaryote_example_file from pycirclize.parser import Genbank # Load Genbank file gbk_file = load_prokaryote_example_file("enterobacteria_phage.gbk") gbk = Genbank(gbk_file) # Initialize circos instance seqid2size = gbk.get_seqid2size() space = 0 if len(seqid2size) == 1 else 2 circos = Circos(sectors=seqid2size, space=space) circos.text("Enterobacteria phage\n(NC_000902)", size=15) seqid2features = gbk.get_seqid2features("CDS") for sector in circos.sectors: # Setup outer track outer_track = sector.add_track((99.7, 100)) outer_track.axis(fc="black") outer_track.xticks_by_interval(5000, label_formatter=lambda v: f"{v / 1000:.0f} Kb") outer_track.xticks_by_interval(1000, tick_length=1, show_label=False) # Plot forward & reverse CDS genomic features cds_track = sector.add_track((93, 98)) for feature in seqid2features[sector.name]: color = "salmon" if feature.location.strand == 1 else "skyblue" cds_track.genomic_features(feature, plotstyle="arrow", fc=color) fig = circos.plotfig() ``` -------------------------------- ### Load Genbank File using PyCirclize Source: https://github.com/moshi4/pycirclize/blob/main/docs/circos_plot.ipynb This Python code snippet demonstrates how to load a Genbank file using the pycirclize library. It imports necessary components and uses a utility function to load an example Genbank file, preparing it for further analysis or visualization. ```python from pycirclize import Circos from pycirclize.parser import Genbank from pycirclize.utils import load_prokaryote_example_file import numpy as np from matplotlib.patches import Patch from matplotlib.lines import Line2D # Load Genbank file gbk_file = load_prokaryote_example_file("escherichia_coli.gbk.gz") gbk = Genbank(gbk_file) ``` -------------------------------- ### PyCircos: Plotting Scatter Points Source: https://github.com/moshi4/pycirclize/blob/main/docs/plot_api_example.ipynb This example demonstrates how to create a scatter plot on a circos track using pycirclize. It plots random data points within the track's defined range and size. ```python from pycirclize import Circos import numpy as np np.random.seed(0) sectors = {"A": 10, "B": 20, "C": 15} circos = Circos(sectors, space=5) for sector in circos.sectors: track = sector.add_track((80, 100), r_pad_ratio=0.1) track.axis() track.xticks_by_interval(1) vmin, vmax = 0, 10 x = np.linspace(track.start, track.end, int(track.size) * 5 + 1) y = np.random.randint(vmin, vmax, len(x)) track.scatter(x, y) fig = circos.plotfig() ``` -------------------------------- ### Parse Genbank Data for Circos Plot (Genomics) Source: https://github.com/moshi4/pycirclize/blob/main/README.md This example shows how to fetch Genbank data using pyCirclize's utility function and parse it using the `Genbank` class. This is a preliminary step for creating genomic visualizations with pyCirclize. Requires `pycirclize`. ```python from pycirclize import Circos from pycirclize.utils import fetch_genbank_by_accid from pycirclize.parser import Genbank # Download `NC_002483` E.coli plasmid genbank gbk_fetch_data = fetch_genbank_by_accid("NC_002483") gbk = Genbank(gbk_fetch_data) ``` -------------------------------- ### PyCircos: Plotting Axes and Grid Lines Source: https://github.com/moshi4/pycirclize/blob/main/docs/plot_api_example.ipynb This example shows how to add axes and grid lines to tracks within a circos plot. It demonstrates plotting Y-axis grid lines, X-axis grid lines with specific intervals, and combined XY-axis grid lines with customizable colors and styles. ```python from pycirclize import Circos import numpy as np np.random.seed(0) sectors = {"A": 10, "B": 20, "C": 15} circos = Circos(sectors, space=5) for sector in circos.sectors: # Plot Y-axis grid line (Default: 6 grid line) track1 = sector.add_track((80, 100), r_pad_ratio=0.1) track1.axis() track1.xticks_by_interval(interval=1) track1.grid() # Plot X-axis grid line (interval=1) track2 = sector.add_track((55, 75)) track2.axis() track2.grid(y_grid_num=None, x_grid_interval=1, color="red") # Plot both XY-axis grid line track3 = sector.add_track((30, 50)) track3.grid(y_grid_num=11, x_grid_interval=0.5, color="blue", ls="dashed") fig = circos.plotfig() ``` -------------------------------- ### PyCircos: Drawing Lines within Sectors Source: https://github.com/moshi4/pycirclize/blob/main/docs/plot_api_example.ipynb Shows how to draw various lines within PyCircos sectors, including full radial lines, partial lines defined by start and end points, and styled lines with different colors, widths, and styles. Requires the pycirclize library. ```python from pycirclize import Circos sectors = {"A": 10, "B": 20, "C": 15} circos = Circos(sectors, space=5) for sector in circos.sectors: sector.axis() sector.line(r=90) sector_center = (sector.start + sector.end) / 2 sector.line(r=80, end=sector_center, color="red") sector.line(r=80, start=sector_center, color="blue") sector.line(r=60, color="green", lw=2, ls="dotted") fig = circos.plotfig() ``` -------------------------------- ### Advanced Radar Chart Customization with pyCirclize Source: https://github.com/moshi4/pycirclize/blob/main/docs/radar_chart.ipynb Demonstrates advanced customization options for radar charts, including custom line styles, fill, marker properties, colormaps, grid formatting, and text labels. It requires pycirclize, pandas, and matplotlib. The output is a complex radar chart with a legend and title. ```python from pycirclize import Circos import pandas as pd # Create RPG jobs parameter dataframe (4 jobs, 8 parameters) df = pd.DataFrame( data=[ [80, 80, 80, 80, 80, 80, 80, 80], [90, 20, 95, 95, 30, 30, 80, 70], [60, 90, 20, 20, 100, 90, 50, 70], [70, 50, 60, 40, 60, 40, 100, 60], ], index=["Hero", "Warrior", "Wizard", "Assassin"], columns=["HP", "MP", "ATK", "DEF", "SP.ATK", "SP.DEF", "SPD", "LUK"], ) print(df) # Define line keyword arguments handler def line_kws_handler(col_name: str): if col_name == "Hero": return dict(ls="dotted", lw=2.0) else: return dict(ls="solid", lw=1.5) # Initialize Circos instance for radar chart plot circos = Circos.radar_chart( df, vmax=100, fill=False, marker_size=6, bg_color=None, cmap=dict(Hero="salmon", Warrior="skyblue", Wizard="lime", Assassin="magenta"), grid_interval_ratio=0.1, grid_label_formatter=lambda v: f"{v:.1f}pt", label_kws_handler=lambda _: dict(style="italic"), line_kws_handler=line_kws_handler, marker_kws_handler=lambda _: dict(marker="s", ec="grey", lw=0.5), ) circos.text("RPG Jobs Radar Chart", r=125, size=15, weight="bold") # Plot figure & set legend on upper right fig = circos.plotfig() _ = circos.ax.legend( loc="upper right", handlelength=2, bbox_to_anchor=(1.05, 1.05), fontsize=10, title="RPG Jobs", ) ``` -------------------------------- ### Combining Data Tracks and Link Plots with pyCirclize Source: https://github.com/moshi4/pycirclize/blob/main/docs/getting_started.ipynb This example showcases how to integrate various data tracks (line, scatter, bar) with link plots in a Circos visualization using pyCirclize. It demonstrates initializing sectors, adding different track types, and plotting links between them with customizable styles. ```python from pycirclize import Circos import numpy as np np.random.seed(0) # Initialize Circos sectors sectors = {"A": 10, "B": 15, "C": 12, "D": 20, "E": 15} circos = Circos(sectors, space=5) for sector in circos.sectors: # Plot sector name sector.text(f"Sector: {sector.name}", r=110, size=15) # Create x positions & randomized y values x = np.arange(sector.start, sector.end) + 0.5 y = np.random.randint(0, 100, len(x)) # Plot line track line_track = sector.add_track((80, 100), r_pad_ratio=0.1) line_track.xticks_by_interval(interval=1) line_track.axis() line_track.line(x, y) # Plot points track points_track = sector.add_track((55, 75), r_pad_ratio=0.1) points_track.axis() points_track.scatter(x, y) # Plot bar track bar_track = sector.add_track((30, 50), r_pad_ratio=0.1) bar_track.axis() bar_track.bar(x, y) # Plot links circos.link(("A", 0, 3), ("B", 15, 12)) circos.link(("B", 0, 3), ("C", 7, 11), color="skyblue") circos.link(("C", 2, 5), ("E", 15, 12), color="chocolate", direction=1) circos.link(("D", 3, 5), ("D", 18, 15), color="lime", ec="black", lw=0.5, hatch="//", direction=2) circos.link(("D", 8, 10), ("E", 2, 8), color="violet", ec="red", lw=1.0, ls="dashed") fig = circos.plotfig() ``` -------------------------------- ### Initialize Circos from BED and Add Cytoband Tracks (Python) Source: https://github.com/moshi4/pycirclize/blob/main/docs/circos_plot.ipynb This example shows how to initialize a Circos object from a BED file containing chromosome information and then add cytoband tracks using a separate cytoband file. It's useful for creating a basic circular genome visualization with standard chromosome boundaries. The `load_eukaryote_example_dataset` function is used for convenience. ```python from pycirclize import Circos from pycirclize.utils import load_eukaryote_example_dataset # Load mm10 dataset (https://github.com/moshi4/pycirclize-data/tree/main/eukaryote/mm10) chr_bed_file, cytoband_file, _ = load_eukaryote_example_dataset("mm10") # Initialize Circos from BED chromosomes circos = Circos.initialize_from_bed(chr_bed_file, space=3) circos.text("Mus musculus (mm10)", size=15) # Add cytoband tracks from cytoband file circos.add_cytoband_tracks((95, 100), cytoband_file) # Plot chromosome name for sector in circos.sectors: sector.text(sector.name, size=10) fig = circos.plotfig() ``` -------------------------------- ### PyCircos: Adding Raster Images and Text to Sectors Source: https://github.com/moshi4/pycirclize/blob/main/docs/plot_api_example.ipynb Explains how to embed raster images (like PNGs) and text labels within PyCircos sectors. It shows positioning images at specific radii, scaling them, auto-rotating them, and adding borders, as well as placing text labels. Requires the pycirclize library and its example image loading utility. ```python from pycirclize import Circos from pycirclize.utils import load_example_image_file sectors = {"A": 10, "B": 15, "C": 12, "D": 20, "E": 15} circos = Circos(sectors, space=5) for sector in circos.sectors: # Plot line in sector region sector.axis(ec="grey") for r in range(10, 100, 10): sector.line(r=r, ec="lightgrey") # Plot raster image (python logo) logo_file = load_example_image_file("python_logo.png") sector.raster(logo_file, r=110, label=sector.name) sector.raster(logo_file, r=50, size=0.1, rotation="auto", border_width=5) sector.text(sector.name, r=62) fig = circos.plotfig() ``` -------------------------------- ### Create Stacked Bar Chart in Circular Layout with pycirclize Source: https://context7.com/moshi4/pycirclize/llms.txt This example shows how to display stacked categorical data within a circular layout using pycirclize and pandas. It creates a stacked bar track for each category and adds category labels and a legend. Dependencies include pycirclize, pandas, and matplotlib. ```python from pycirclize import Circos import pandas as pd # Create stacked data (categories x positions) categories = ["Cat1", "Cat2", "Cat3", "Cat4"] positions = list(range(20)) data = {cat: [abs(hash(f"{cat}{i}")) % 100 for i in positions] for cat in categories} df = pd.DataFrame(data, index=positions) # Setup Circos sectors = {"Data": len(positions)} circos = Circos(sectors, space=0) for sector in circos.sectors: # Create stacked bar track track = sector.add_track((70, 100), r_pad_ratio=0.1) track.axis() track.stacked_bar( df.T, # transpose: rows=categories, cols=positions width=0.8, cmap="Set3", show_value=False ) # Add category labels track.text("Stacked Bar Chart", r=110, size=14) # Add legend import matplotlib.patches as mpatches from matplotlib import cm cmap = cm.get_cmap("Set3") handles = [ mpatches.Patch(color=cmap(i/len(categories)), label=cat) for i, cat in enumerate(categories) ] fig = circos.plotfig() circos.ax.legend(handles=handles, loc="upper right", fontsize=9) fig.savefig("stacked_bar.png") ``` -------------------------------- ### Generate Circos Plot using pyCirclize Source: https://github.com/moshi4/pycirclize/blob/main/README.md This example demonstrates how to generate a Circos Plot using the pyCirclize library in Python. It involves initializing sectors, adding tracks for lines, scatter plots, and bars, and plotting links between sectors. The visualization is saved as a PNG file. Requires `numpy` and `pycirclize`. ```python from pycirclize import Circos import numpy as np np.random.seed(0) # Initialize Circos sectors sectors = {"A": 10, "B": 15, "C": 12, "D": 20, "E": 15} circos = Circos(sectors, space=5) for sector in circos.sectors: # Plot sector name sector.text(f"Sector: {sector.name}", r=110, size=15) # Create x positions & random y values x = np.arange(sector.start, sector.end) + 0.5 y = np.random.randint(0, 100, len(x)) # Plot lines track1 = sector.add_track((80, 100), r_pad_ratio=0.1) track1.xticks_by_interval(interval=1) track1.axis() track1.line(x, y) # Plot points track2 = sector.add_track((55, 75), r_pad_ratio=0.1) track2.axis() track2.scatter(x, y) # Plot bars track3 = sector.add_track((30, 50), r_pad_ratio=0.1) track3.axis() track3.bar(x, y) # Plot links circos.link(("A", 0, 3), ("B", 15, 12)) circos.link(("B", 0, 3), ("C", 7, 11), color="skyblue") circos.link(("C", 2, 5), ("E", 15, 12), color="chocolate", direction=1) circos.link(("D", 3, 5), ("D", 18, 15), color="lime", ec="black", lw=0.5, hatch="//", direction=2) circos.link(("D", 8, 10), ("E", 2, 8), color="violet", ec="red", lw=1.0, ls="dashed") circos.savefig("example01.png") ``` -------------------------------- ### Manual Legend Plotting with pyCirclize and Matplotlib Source: https://github.com/moshi4/pycirclize/blob/main/docs/plot_tips.ipynb This example demonstrates how to manually create legends for pyCirclize plots by leveraging Matplotlib's `Axes.legend()` method. It shows how to add different types of plot elements (lines, scatters, rectangles) with corresponding colors and markers, and then manually construct legend entries using `Patch` and `Line2D` objects. ```python from pycirclize import Circos from pycirclize.utils import ColorCycler from matplotlib.patches import Patch from matplotlib.lines import Line2D import numpy as np np.random.seed(0) line_colors = ("red", "blue", "green") scatter_colors = ("orange", "purple", "black") scatter_markers = ("o", "^", "+") cmap_name = "tab10" sectors = dict(A=10, B=15, C=12) circos = Circos(sectors, space=5) for sector in circos.sectors: sector.text(sector.name, r=110, size=12) # Plot line track track1 = sector.add_track((80, 100), r_pad_ratio=0.1) track1.axis() track1.xticks_by_interval(interval=1) for line_color in line_colors: x = np.arange(sector.start, sector.end) + 0.5 y = np.random.randint(0, 100, len(x)) track1.line(x, y, vmax=100, color=line_color) # Plot scatter track track2 = sector.add_track((55, 75), r_pad_ratio=0.1) track2.axis() for color, marker in zip(scatter_colors, scatter_markers): point_num = 10 x = np.random.rand(point_num) * (sector.end - 1) + 0.5 y = np.random.rand(point_num) * 10 track2.scatter(x, y, vmax=10, c=color, marker=marker, s=15) # Plot rect track track3 = sector.add_track((47, 50)) ColorCycler.set_cmap(cmap_name) for idx in range(int(sector.start), int(sector.end)): track3.rect(idx, idx + 1, color=ColorCycler(), ec="black", lw=0.5) fig = circos.plotfig() ``` -------------------------------- ### Visualize Links with Styles in pycirclize Source: https://context7.com/moshi4/pycirclize/llms.txt Demonstrates how to create links between sectors in a circular layout with various styling options, including color, direction, radius, and line styles. It requires the pycirclize library. ```python from pycirclize import Circos # Setup sectors sectors = {"A": 10, "B": 20, "C": 15, "D": 25} circos = Circos(sectors, space=5) for sector in circos.sectors: track = sector.add_track((95, 100)) track.axis(fc="lightgrey") track.text(sector.name, size=12) track.xticks_by_interval(1) # Basic link circos.link(("A", 0, 3), ("B", 15, 12), color="grey", alpha=0.5) # Colored link with direction arrow circos.link( ("B", 5, 8), ("C", 3, 7), color="skyblue", direction=1, alpha=0.7 ) # Link with custom radius and styling circos.link( ("C", 10, 13), ("D", 5, 10), r1=90, r2=95, # custom start/end radius color="violet", ec="red", lw=2, ls="dashed" ) # Bidirectional link with hatch pattern circos.link( ("D", 15, 18), ("A", 6, 9), color="lime", ec="black", lw=1, hatch="//", direction=2, alpha=0.6 ) # Link with custom height (Bezier curve) circos.link( ("A", 2, 4), ("D", 20, 23), color="orange", height_ratio=0.8, alpha=0.5 ) circos.savefig("styled_links.png") ``` -------------------------------- ### Set Sectors with Custom Start and End Degrees in pyCirclize Source: https://github.com/moshi4/pycirclize/blob/main/docs/getting_started.ipynb Initializes a circular layout with specified sector sizes, inter-sector spacing, and custom start and end degrees. It then plots the axis and text for each sector. This allows for fine-tuning the angular range of the circular plot. ```python from pycirclize import Circos # Initialize circos sectors sectors = {"A": 10, "B": 15, "C": 12, "D": 20, "E": 15} circos = Circos(sectors, space=5, start=-270, end=30) # Set start-end degree ranges for sector in circos.sectors: # Plot sector axis & name text sector.axis(fc="none", ls="dashdot", lw=2, ec="black", alpha=0.5) sector.text(f"Sector: {sector.name}={sector.size}", size=15) fig = circos.plotfig() ``` -------------------------------- ### Helper Functions and Classes Source: https://github.com/moshi4/pycirclize/blob/main/docs/api-docs/utils.md This section covers helper functions for calculating group spaces and the ColorCycler class for managing color palettes. ```APIDOC ## Helper Functions and Classes ### Description Utility functions and classes that assist in various aspects of data manipulation and visualization within pycirclize. ### Endpoint `/moshi4/pycirclize/utils/helper` ### Functions/Classes #### `calc_group_spaces(data: list, total_space: int, padding: int)` * **Description**: Calculates the spacing for groups within a given total space, considering padding. * **Method**: Not Applicable (Function) * **Parameters**: * `data` (list) - Required - The data for which to calculate group spaces. * `total_space` (int) - Required - The total available space. * `padding` (int) - Required - The padding to apply. #### `ColorCycler` * **Description**: A class for cycling through a predefined list of colors, useful for consistent color assignment in plots. * **Method**: Not Applicable (Class) * **Usage**: Instantiate the class and call its methods to get the next color in the sequence. ```