### Highlighting ROIs with Netplotbrain Source: https://github.com/wiheto/netplotbrain/blob/main/docs/gallery/highlight_roi.ipynb Load necessary libraries, define atlas regions, and prepare node information to highlight specific seeds. This example uses a 100-node atlas and specifies two seeds to be highlighted with different colors. ```python # Load imports import netplotbrain import pandas as pd import numpy as np # Get 100 node atlas from templateflow node_dict = {'atlas': 'Schaefer2018', 'desc': '100Parcels7Networks', 'extension': '.nii.gz', 'resolution': 1} # pyton index of atlas rois. # this will start at 0 but atlas starts at 1. # So below select node 15 and 66 in atlas. seeds = [14, 65] # Create dataframe of 100 rois nodeinfo = np.zeros(100) nodeinfo[seeds] = 1 node_color = ['gray'] * 100 node_color[seeds[0]] = 'cornflowerblue' node_color[seeds[1]] = 'salmon' nodes_df = pd.DataFrame({'seed': nodeinfo, 'color': node_color}) fig, _ = netplotbrain.plot(template = 'MNI152NLin2009cAsym', nodes = node_dict, nodes_df = nodes_df, node_type = 'parcels', view = 'preset-3', node_color = 'color', highlight_nodes = 'seed', highlighlevel = 1, node_alpha = 0.4, save_name='/home/xthowi/scratch/sham.png', figdpi=300) ``` -------------------------------- ### Import Libraries for Netplotbrain and bctpy Source: https://github.com/wiheto/netplotbrain/blob/main/docs/gallery/nbs.ipynb Import necessary libraries including bctpy for network statistics, numpy for data manipulation, matplotlib for plotting, and netplotbrain for visualization. This setup is required before proceeding with NBS analysis. ```python import bct import numpy as np import matplotlib.pyplot as plt import netplotbrain ``` -------------------------------- ### Plotting Nodes and Edges with Numpy Array (Implicit) Source: https://github.com/wiheto/netplotbrain/blob/main/docs/tutorial/tutorial1_input.ipynb Plots nodes and edges. This example assumes edges are provided as a numpy array (NxN adjacency matrix) or a pandas DataFrame with 'i', 'j', and optional 'weight' columns. Node colors can be mapped to a column, and node scale can be adjusted. Requires nodes and edges to be defined. ```python # Import packages # Define the nodes (5 example nodes) nodes_df = pd.DataFrame(data={'x': [40, 10, 30, -15, -25], 'y': [50, 40, -10, -20, 20], 'z': [20, 30, -10, -15, 30], 'communities': [1, 1, 1, 2, 2], 'degree_centrality': [1, 1, 0.2, 0.8, 0.4]}) # Define the edges edges_df = pd.DataFrame(data={'i': [0, 0, 1, 1, 3], 'j': [1, 2, 2, 3, 4]}) # Call netplotbrain to plot netplotbrain.plot( nodes=nodes_df, edges=edges_df, node_color='communities', arrowaxis=None, node_scale=150) ``` -------------------------------- ### Plotting Multiple Views on a Matplotlib Figure Source: https://context7.com/wiheto/netplotbrain/llms.txt This example demonstrates how to plot multiple views of brain network data onto a single matplotlib figure, utilizing different axes for each view. Ensure matplotlib and pandas are installed. ```python import netplotbrain import matplotlib.pyplot as plt import pandas as pd nodes = pd.read_csv( 'https://raw.githubusercontent.com/wiheto/netplotbrain/main/examples/example_nodes.tsv', sep='\t', index_col=0) fig = plt.figure(figsize=(12, 4)) ax1 = fig.add_subplot(131, projection='3d') ax2 = fig.add_subplot(132, projection='3d') ax3 = fig.add_subplot(133, projection='3d') for ax, view_angle in zip([ax1, ax2, ax3], ['L', 'S', 'R']): netplotbrain.plot( template='MNI152NLin2009cAsym', nodes=nodes, template_style='glass', view=view_angle, fig=fig, ax=ax, arrowaxis=None, showlegend=False ) fig.suptitle('Three views', fontsize=14) plt.tight_layout() plt.savefig('three_views.png', dpi=150) ``` -------------------------------- ### Apply Different Template Styles Source: https://context7.com/wiheto/netplotbrain/llms.txt Compares four rendering styles ('glass', 'surface', 'filled', 'cloudy') side-by-side and demonstrates transparency tuning and speed optimization for 'filled' style. ```python import netplotbrain # Compare all four styles side-by-side in one call fig, ax = netplotbrain.plot( template='MNI152NLin6Asym', template_style=['surface', 'filled', 'cloudy', 'glass'], view='A', arrowaxis=None ) ``` ```python import netplotbrain # Glass brain with transparency tuning fig, ax = netplotbrain.plot( template='MNI152NLin2009cAsym', template_style='glass', template_alpha=0.3, template_glass_maxalpha=0.02, # controls smoky transparency view='L' ) ``` ```python import netplotbrain # Speed up filled rendering with larger voxels (trade resolution for speed) fig, ax = netplotbrain.plot( template='MNI152NLin6Asym', template_style='filled', template_voxelsize=3, # default is 2; larger = faster view='L' ) ``` -------------------------------- ### Load Connectivity from BIDS using edges_from_bids Source: https://context7.com/wiheto/netplotbrain/llms.txt Loads and aggregates connectivity matrices from BIDS derivatives. Supports averaging, Fisher-z averaging, group subtraction, and grouping by metadata. Requires specifying the path to the BIDS dataset and derivatives directory. ```python from netplotbrain import edges_from_bids import netplotbrain # Average all subjects' connectivity matrices edges, info = edges_from_bids( path='/data/bids_dataset', derivative='/data/bids_dataset/derivatives/connectivity', operation='avg' # 'avg', 'zavg', 'avg_subtract', or None for per-subject ) # info = {'operation': 'avg', 'groups': ['all'], 'files_found': 12, ...} # Group subtract: group1 minus group2 (group column from participants.tsv) edges, info = edges_from_bids( path='/data/bids_dataset', derivative='/data/bids_dataset/derivatives/connectivity', operation='avg_subtract', groups='group' # column name in participants.tsv ) # edges = {'group1 minus group2': pd.DataFrame(...), ...} # Plot the averaged result nodes_df = ... # load or define node coordinates fig, ax = netplotbrain.plot( template='MNI152NLin2009cAsym', nodes=nodes_df, edges=edges, template_style='glass', view='LSR' ) ``` -------------------------------- ### Edge Input: NumPy Adjacency Matrix Source: https://context7.com/wiheto/netplotbrain/llms.txt Provide edges directly as a square NxN NumPy array. Edge weights are determined by the matrix values. Ensure node data is loaded appropriately, for example, using pandas. ```python import netplotbrain import numpy as np import pandas as pd nodes_df = pd.read_csv( 'https://raw.githubusercontent.com/wiheto/netplotbrain/main/examples/example_nodes.tsv', sep='\t', index_col=0 ) ``` -------------------------------- ### Import necessary packages Source: https://github.com/wiheto/netplotbrain/blob/main/docs/gallery/plot_connectivitymatrix.ipynb Imports the required libraries for template management, network plotting, and data manipulation. ```python # Import packages import templateflow.api as tf import netplotbrain import pandas as pd ``` -------------------------------- ### GIF Keyword Arguments Source: https://github.com/wiheto/netplotbrain/blob/main/docs/api.md Arguments for creating animated GIF files from views. ```APIDOC ## GIF Keyword Arguments ### Description Arguments for creating animated GIF files from views. ### Arguments - **gif** (bool) - If `True`, saves views as a GIF. - **gif_duration** (int) - Duration of each frame in the GIF in milliseconds. - **gif_loop** (int) - Number of times the GIF should loop. `0` (default) means infinite loop. ``` -------------------------------- ### Plotting with WHS Template - Netplotbrain Source: https://github.com/wiheto/netplotbrain/blob/main/docs/gallery/whs.ipynb Imports necessary libraries, loads example node and edge data, rescales node coordinates for the WHS template, and plots the network. Use this to visualize brain networks on the WHS template. ```python # Import packages import netplotbrain import pandas as pd #Path to node and edge example data on netplotbrain nodepath = 'https://raw.githubusercontent.com/wiheto/netplotbrain/main/examples/example_nodes.tsv' edgepath = 'https://raw.githubusercontent.com/wiheto/netplotbrain/main/examples/example_edges.tsv' # Load example data nodes = pd.read_csv(nodepath, sep='\t', index_col=0) edges = pd.read_csv(edgepath, sep='\t', index_col=0) # Rescale example node data to fit template nodes_whs = nodes.copy() nodes_whs['x'] = nodes_whs['x'] / 8 nodes_whs['y'] = nodes_whs['y'] / 8 nodes_whs['z'] = nodes_whs['z'] / 8 # Plot figure netplotbrain.plot(template='WHS', template_style='surface', title='Multiple templates possible', view='LSR', nodes=nodes_whs, node_size='centrality_measure1', edges=edges, node_color='community', node_scale=80, template_voxelsize=0.2) ``` -------------------------------- ### Prepare DMN highlighting Source: https://github.com/wiheto/netplotbrain/blob/main/docs/gallery/plot_dmn.ipynb Identify and mark nodes belonging to the Default Mode Network (DMN) by creating a boolean column. Non-DMN nodes are colored white for potential transparency. ```python # Now we need to make a colour argument for the DMN nodes only # Get which rows are in the default mode network atlas_df['defaultmode'] = atlas_df['name'].str.contains('Default') # Set the color column of non DMN nodes to same colour # Not really necessary cause we make these nods transparant below atlas_df.loc[~atlas_df['defaultmode'], 'color'] = 'white' ``` -------------------------------- ### Applying Template Styles with `template_style` Source: https://context7.com/wiheto/netplotbrain/llms.txt Details the different rendering styles available for brain templates, including 'glass', 'surface', 'filled', and 'cloudy'. ```APIDOC ## netplotbrain.plot with `template_style` parameter ### Description Applies different rendering styles to the brain template. Available styles include 'glass' (semi-transparent), 'surface' (surface mesh), 'filled' (solid voxels), and 'cloudy' (edge-scatter outline). Styles can be applied per subplot. ### Method `netplotbrain.plot` ### Parameters #### Path Parameters None explicitly mentioned. #### Query Parameters None explicitly mentioned. #### Request Body None explicitly mentioned. ### Request Example ```python import netplotbrain # Compare all four styles side-by-side in one call # fig, ax = netplotbrain.plot( # template='MNI152NLin6Asym', # template_style=['surface', 'filled', 'cloudy', 'glass'], # view='A', # arrowaxis=None # ) # Glass brain with transparency tuning # fig, ax = netplotbrain.plot( # template='MNI152NLin2009cAsym', # template_style='glass', # template_alpha=0.3, # template_glass_maxalpha=0.02, # controls smoky transparency # view='L' # ) # Speed up filled rendering with larger voxels # fig, ax = netplotbrain.plot( # template='MNI152NLin6Asym', # template_style='filled', # template_voxelsize=3, # default is 2; larger = faster # view='L' # ) ``` ### Response #### Success Response (200) Returns a matplotlib figure and axes object with the specified template styles applied. #### Response Example ```json { "figure": "matplotlib.figure.Figure", "axes": "matplotlib.axes.Axes" } ``` ``` -------------------------------- ### Plotting nodes with categorical and continuous coloring Source: https://context7.com/wiheto/netplotbrain/llms.txt Demonstrates plotting nodes with categorical data using the 'Pastel1' colormap and continuous data using the 'inferno' colormap. Requires pre-defined nodes and an atlas DataFrame. ```python fig, _ = netplotbrain.plot(nodes=nodes, nodes_df=atlas_df, node_type='parcels', node_color='network', node_cmap='Pastel1', view='S', fig=fig, ax=ax2, showlegend=False) ``` ```python fig, _ = netplotbrain.plot(nodes=nodes, nodes_df=atlas_df, node_type='parcels', node_color='centrality', node_cmap='inferno', view='S', fig=fig, ax=ax3, showlegend=False) ``` -------------------------------- ### Import Libraries and Load Atlas Data Source: https://github.com/wiheto/netplotbrain/blob/main/docs/gallery/node_cmap.ipynb Imports necessary libraries and loads atlas information using TemplateFlow. This is a prerequisite for creating visualizations. ```python # Import necessary packages import netplotbrain import pandas as pd import templateflow.api as tf ``` ```python # Load templateflow information about the Schaefer atlas atlasinfo = tf.get(template='MNI152NLin2009cAsym', atlas='Schaefer2018', desc='100Parcels7Networks', extension='.tsv') atlas_df = pd.read_csv(str(atlasinfo), sep=' ') atlas_df.head() ``` -------------------------------- ### Render Nodes as Circles, Spheres, or Parcels Source: https://context7.com/wiheto/netplotbrain/llms.txt Illustrates how to render nodes using different types: 'circles' (2D markers), 'spheres' (3D volumetric), and 'parcels' (filled atlas regions). ```python import netplotbrain import matplotlib.pyplot as plt fig = plt.figure() # Circles ax = fig.add_subplot(131, projection='3d') netplotbrain.plot( nodes={'atlas': 'Schaefer2018', 'desc': '100Parcels7Networks', 'resolution': 1}, template='MNI152NLin6Asym', template_style='glass', view='S', node_type='circles', node_scale=40, fig=fig, ax=ax ) ``` ```python import netplotbrain import matplotlib.pyplot as plt fig = plt.figure() # Spheres ax = fig.add_subplot(132, projection='3d') netplotbrain.plot( nodes={'atlas': 'Schaefer2018', 'desc': '100Parcels7Networks', 'resolution': 1}, template='MNI152NLin6Asym', template_style='glass', view='S', node_type='spheres', fig=fig, ax=ax ) ``` ```python import netplotbrain import matplotlib.pyplot as plt fig = plt.figure() # Parcels (renders atlas as filled 3D regions) ax = fig.add_subplot(133, projection='3d') netplotbrain.plot( nodes={'atlas': 'Schaefer2018', 'desc': '100Parcels7Networks', 'resolution': 1}, template='MNI152NLin6Asym', template_style=None, view='S', node_type='parcels', node_color='tab20c', fig=fig, ax=ax ) ``` -------------------------------- ### Plotting with Different Template Styles Source: https://github.com/wiheto/netplotbrain/blob/main/docs/gallery/template_styles.ipynb Demonstrates how to apply various template styles (surface, filled, cloudy, glass) to a Netplotbrain plot. Requires importing netplotbrain and matplotlib.pyplot. ```python import netplotbrain import matplotlib.pyplot as plt netplotbrain.plot(template='MNI152NLin6Asym', template_style=['surface', 'filled', 'cloudy', 'glass'], view='A', arrowaxis=None) ``` -------------------------------- ### Import Libraries Source: https://github.com/wiheto/netplotbrain/blob/main/docs/gallery/simple.ipynb Import necessary libraries for data manipulation and plotting. ```python # Load imports import netplotbrain import pandas as pd ``` -------------------------------- ### Define Data Paths Source: https://github.com/wiheto/netplotbrain/blob/main/docs/gallery/simple.ipynb Specify the paths to the node and edge data files. ```python #Path to node and edge example data on netplotbrain nodepath = 'https://raw.githubusercontent.com/wiheto/netplotbrain/main/examples/example_nodes.tsv' edgepath = 'https://raw.githubusercontent.com/wiheto/netplotbrain/main/examples/example_edges.tsv' ``` -------------------------------- ### Import Necessary Packages Source: https://github.com/wiheto/netplotbrain/blob/main/docs/gallery/specifying_node_color.ipynb Imports the required libraries for data manipulation, plotting, and atlas information retrieval. ```python # Import packages import templateflow.api as tf import netplotbrain import pandas as pd import numpy as np import matplotlib.pyplot as plt ``` -------------------------------- ### Controlling Views with the `view` Parameter Source: https://context7.com/wiheto/netplotbrain/llms.txt Explains how to use the `view` parameter to specify different viewing angles and subplot arrangements for brain visualizations. ```APIDOC ## netplotbrain.plot with `view` parameter ### Description Controls the viewing angles and subplot layout of the brain visualization. The `view` parameter accepts strings for single views, combined strings for rows of subplots, and lists for multi-row grids. ### Method `netplotbrain.plot` ### Parameters #### Path Parameters None explicitly mentioned. #### Query Parameters None explicitly mentioned. #### Request Body None explicitly mentioned. ### Request Example ```python import netplotbrain # Multi-angle rows: Left, Superior, Right (top row) + Anterior, Inferior, Posterior (bottom row) # fig, ax = netplotbrain.plot( # template='MNI152NLin2009cAsym', # template_style='surface', # view=['LSR', 'AIP'] # list → two rows of subplots # ) # Rotating sequence from Anterior to Posterior in 5 frames # fig, ax = netplotbrain.plot( # template='MNI152NLin2009cAsym', # template_style='surface', # view='AP', # frames=5 # ) # Full 360° rotation in 8 frames # fig, ax = netplotbrain.plot( # template='MNI152NLin2009cAsym', # template_style='glass', # view='360', # frames=8 # ) ``` ### Response #### Success Response (200) Returns a matplotlib figure and axes object with the specified views rendered. #### Response Example ```json { "figure": "matplotlib.figure.Figure", "axes": "matplotlib.axes.Axes" } ``` ``` -------------------------------- ### Core Plotting Functionality with NetPlotBrain Source: https://context7.com/wiheto/netplotbrain/llms.txt Use `netplotbrain.plot()` as the main entry point for visualizations. It accepts template, node, and edge data to render a 3D matplotlib figure. Ensure necessary libraries like netplotbrain and pandas are imported. ```python import netplotbrain import pandas as pd # Load example node and edge data nodepath = 'https://raw.githubusercontent.com/wiheto/netplotbrain/main/examples/example_nodes.tsv' edgepath = 'https://raw.githubusercontent.com/wiheto/netplotbrain/main/examples/example_edges.tsv' nodes = pd.read_csv(nodepath, sep='\t', index_col=0) edges = pd.read_csv(edgepath, sep='\t', index_col=0) # Plot on MNI template with default left-hemisphere view fig, ax = netplotbrain.plot( template='MNI152NLin2009cAsym', nodes=nodes, edges=edges ) # Returns: (matplotlib.figure.Figure, list of matplotlib axes) ``` -------------------------------- ### Create and Modify Connectivity Matrix Source: https://github.com/wiheto/netplotbrain/blob/main/docs/gallery/spring_layout.ipynb Generates a random connectivity matrix and then strengthens the connections within each network community. ```python # create empty cognitive matrix edges = np.random.normal(0, 0.025, [100, 100]) # Set within network connectivity to be stronger for network in atlasinfo['yeo7networks'].unique(): idx = atlasinfo[atlasinfo['yeo7networks']==network].index idx_pairs = np.array(list(itertools.combinations(idx, 2))) edges[idx_pairs[:, 0], idx_pairs[:, 1]] = np.random.normal(0.5, 0.025, [len(idx_pairs)]) edges[idx_pairs[:, 1], idx_pairs[:, 0]] = np.random.normal(0.5, 0.025, [len(idx_pairs)]) ``` -------------------------------- ### Import Packages Source: https://github.com/wiheto/netplotbrain/blob/main/docs/gallery/node_styles.ipynb Imports the necessary libraries, netplotbrain and matplotlib.pyplot, for plotting. ```python # Import packages import netplotbrain import matplotlib.pyplot as plt ``` -------------------------------- ### Node Input: TemplateFlow Atlas Dictionary Source: https://context7.com/wiheto/netplotbrain/llms.txt Use a TemplateFlow atlas as node input by providing a dictionary of key-value pairs. The atlas NIfTI is automatically downloaded. Set `node_type='parcels'` to render atlas regions as 3D objects. ```python import netplotbrain # Specify a TemplateFlow atlas as nodes nodes = { 'template': 'MNI152NLin2009cAsym', 'atlas': 'Schaefer2018', 'desc': '400Parcels7Networks', 'resolution': 1 } fig, ax = netplotbrain.plot( template='MNI152NLin2009cAsym', nodes=nodes, node_type='parcels', # render atlas parcels as 3D regions instead of circles view='S', # Superior view arrowaxis=None ) ``` -------------------------------- ### Define template and atlas parameters Source: https://github.com/wiheto/netplotbrain/blob/main/docs/gallery/plot_dmn.ipynb Specify the template and atlas details to be used for data retrieval. Ensure these parameters match available data in templateflow. ```python # Get template information template = 'MNI152NLin2009cAsym' atlas = 'Schaefer2018' atlas_desc = '400Parcels7Networks' ``` -------------------------------- ### Create Simple Plot Source: https://github.com/wiheto/netplotbrain/blob/main/docs/gallery/simple.ipynb Generate a plot using the loaded node and edge data with a specified template. ```python netplotbrain.plot(template='MNI152NLin2009cAsym', nodes=nodes, edges=edges) ``` -------------------------------- ### Node Coloring Options Source: https://context7.com/wiheto/netplotbrain/llms.txt Explains how to color nodes using categorical or continuous data from a DataFrame column, or by providing explicit colors. Also covers `node_cmap` for colormaps. ```APIDOC ## netplotbrain.plot with node coloring options ### Description Allows for flexible node coloring based on data. `node_color` can accept a DataFrame column name (for categorical or continuous data), a matplotlib color string, or a list of explicit colors. `node_cmap` specifies the colormap for data-driven coloring. ### Method `netplotbrain.plot` ### Parameters #### Path Parameters None explicitly mentioned. #### Query Parameters None explicitly mentioned. #### Request Body None explicitly mentioned. ### Request Example ```python import templateflow.api as tf import netplotbrain import pandas as pd import numpy as np # atlasinfo = tf.get(template='MNI152NLin2009cAsym', atlas='Schaefer2018', # desc='100Parcels7Networks', extension='.tsv') # atlas_df = pd.read_csv(str(atlasinfo), sep='\t') # atlas_df['network'] = [n.split('_')[2] for n in atlas_df.name] # atlas_df['centrality'] = np.tile(np.arange(0, 10), 10) # nodes = {'template': 'MNI152NLin2009cAsym', 'atlas': 'Schaefer2018', # 'desc': '100Parcels7Networks', 'resolution': 1} # import matplotlib.pyplot as plt # fig = plt.figure() # ax1 = fig.add_subplot(131, projection='3d') # Explicit per-node color column # fig, _ = netplotbrain.plot(nodes=nodes, nodes_df=atlas_df, node_type='parcels', # node_color='color', view='S', fig=fig, ax=ax1, showlegend=False) ``` ### Response #### Success Response (200) Returns a matplotlib figure and axes object with nodes colored according to the specified parameters. #### Response Example ```json { "figure": "matplotlib.figure.Figure", "axes": "matplotlib.axes.Axes" } ``` ``` -------------------------------- ### Initialize Figure Source: https://github.com/wiheto/netplotbrain/blob/main/docs/gallery/node_styles.ipynb Initializes a matplotlib figure to be used for plotting. ```python fig = plt.figure() ``` -------------------------------- ### Load atlas data Source: https://github.com/wiheto/netplotbrain/blob/main/docs/gallery/plot_dmn.ipynb Retrieve the atlas data file (TSV) using templateflow and load it into a pandas DataFrame. The `head()` method displays the first few rows. ```python # Get and load the tsv file atlas_path = tf.get(atlas=atlas, template=template, desc=atlas_desc, extension='.tsv') atlas_df = pd.read_csv(atlas_path, sep=' ') atlas_df.head() ``` -------------------------------- ### Define a Custom Node Colormap Source: https://github.com/wiheto/netplotbrain/blob/main/docs/gallery/node_cmap.ipynb Creates a custom colormap by defining a list of desired colors. This list will be used to color the nodes based on their network affiliation. ```python # Create custom colormap node_cmap = ['blue', 'red', 'green', 'black', 'purple', 'yellow', 'orange'] ``` -------------------------------- ### Run NBS Statistics with bctpy Source: https://github.com/wiheto/netplotbrain/blob/main/docs/gallery/nbs.ipynb Execute the NBS analysis using bctpy's `nbs_bct` function on the generated group connectivity data. Adjust the cluster threshold and permutation count (k) as needed for your analysis. A higher 'k' provides a more accurate null distribution but increases computation time. ```python # g1 and g2 are both (Node, Node, Subject) in size. # The third input argument is the cluster threshold (set far too high here, but to ensure we just get the 2 extreme communities). # Note, k=100 is set for speed purposes. Should be larger. p, adj, null = bct.nbs_bct(g1, g2, 4, k=100, seed=2022) ``` -------------------------------- ### Saving Figures in PNG, SVG, and GIF Formats Source: https://context7.com/wiheto/netplotbrain/llms.txt Saves figures using the 'savename' parameter. Specify file extensions for desired formats (e.g., '.png', '.svg'). Setting 'gif=True' exports an animated GIF. Adjust 'fig_dpi' for resolution and 'gif_duration'/'gif_loop' for GIF properties. ```python import netplotbrain # Save as both PNG and SVG fig, ax = netplotbrain.plot( template='MNI152NLin2009cAsym', template_style='glass', view='360', frames=12, savename='/output/brain_360', # saves brain_360.png and brain_360.svg fig_dpi=300 ) # Export as animated GIF fig, ax = netplotbrain.plot( template='MNI152NLin2009cAsym', template_style='glass', view='360', frames=24, gif=True, gif_duration=100, # milliseconds per frame gif_loop=0, # 0 = infinite loop savename='/output/brain_rotation.gif' ) ``` -------------------------------- ### Using TemplateFlow Atlas as Nodes Source: https://github.com/wiheto/netplotbrain/blob/main/docs/tutorial/tutorial1_input.ipynb Specify nodes by providing a dictionary of TemplateFlow atlas key/value pairs. The atlas will be automatically downloaded. 'arrowaxis=None' is used here for cleaner visualization. ```python # Define the atlas by key value words of TemplateFlow name nodes={'template': 'MNI152NLin2009cAsym', 'atlas': 'Schaefer2018', 'desc': '400Parcels7Networks', 'resolution': 1} ## Template (nifti or string) netplotbrain.plot( nodes=nodes, arrowaxis=None) ``` -------------------------------- ### Load Node Data Source: https://github.com/wiheto/netplotbrain/blob/main/docs/gallery/simple.ipynb Load node data from a TSV file into a pandas DataFrame and display the first few rows. ```python #Example node and edges dataframes included with package nodes = pd.read_csv(nodepath, sep='\t', index_col=0) # peak at first lines of nodes dataframe nodes.head() ``` -------------------------------- ### Import Libraries and Set Seed Source: https://github.com/wiheto/netplotbrain/blob/main/docs/gallery/spring_layout.ipynb Imports necessary libraries for data manipulation, plotting, and Netplotbrain. Sets a random seed for reproducible results. ```python # Import all necessary files import pandas as pd import numpy as np import netplotbrain import matplotlib.pyplot as plt import templateflow.api as tf import itertools # Set random seed for reproducibility np.random.seed(2022) ``` -------------------------------- ### Customizing Node Appearance with DataFrame Properties Source: https://github.com/wiheto/netplotbrain/blob/main/docs/tutorial/tutorial1_input.ipynb Enhance node visualization by mapping DataFrame columns to node properties like 'degree_centrality' for size and 'communities' for color. 'node_scale' adjusts overall node size, and legends are automatically generated. ```python # Define the nodes (5 example nodes) nodes_df = pd.DataFrame(data={'x': [40, 10, 30, -15, -25], 'y': [50, 40, -10, -20, 20], 'z': [20, 30, -10, -15, 30], 'communities': [1, 1, 1, 2, 2], 'degree_centrality': [1, 1, 0.2, 0.8, 0.4]}) # Call netplotbrain to plot netplotbrain.plot( nodes=nodes_df, node_size='degree_centrality', node_color='communities', arrowaxis=None, node_scale=100) ``` -------------------------------- ### Download and Load Atlas Information Source: https://github.com/wiheto/netplotbrain/blob/main/docs/gallery/specifying_node_color.ipynb Downloads atlas information from templateflow and loads it into a pandas DataFrame. This DataFrame is used to extract network information and other node attributes. ```python # Download atlas information from templateflow atlasinfo = tf.get(template='MNI152NLin2009cAsym', atlas='Schaefer2018', desc='100Parcels7Networks', extension='.tsv') atlas_df = pd.read_csv(str(atlasinfo), sep=' ') atlas_df.head() ``` -------------------------------- ### FIGURE Keyword Arguments Source: https://github.com/wiheto/netplotbrain/blob/main/docs/api.md Arguments related to figure creation and saving. ```APIDOC ## FIGURE Keyword Arguments ### Description Arguments for controlling the figure object and saving options. ### Arguments - **ax** (matplotlib 3D ax) - The matplotlib 3D axes object to plot on. Example: `fig = plt.figure(). ax = fig.add_subplot(111, projection='3d'). netplotbrain.plot(ax, ...)` - **fig** (matplotlib figure) - The matplotlib figure object. - **savename** (str) - Save path for the figure. If the string ends with `.png` or `.svg`, it will save only that format. If it ends with anything else, it will save both `.png` and `.svg` figures. Default: `None` (nothing is saved). - **figdpi** (int) - Resolution of the figure when saving PNG files. Default: `300`. ``` -------------------------------- ### Download and Parse Atlas Information Source: https://github.com/wiheto/netplotbrain/blob/main/docs/gallery/spring_layout.ipynb Downloads Schaefer atlas information using TemplateFlow and parses it to extract network names. It renames some networks for brevity. ```python atlas = {'template': 'MNI152NLin2009cAsym', 'atlas': 'Schaefer2018', 'desc': '100Parcels7Networks'} atlasinfo = tf.get(extension='.tsv', **atlas) atlasinfo = pd.read_csv(atlasinfo, sep='\t') # Resolution argument needed in atlas later nii.gz file atlas['resolution'] = 1 # Parse the info in to get network names networks = list(map(lambda x: x.split('_')[2], atlasinfo.name.values)) atlasinfo['yeo7networks'] = networks # Rename longer network names atlasinfo['yeo7networks'].replace('DorsAttn', 'DA', inplace=True) atlasinfo['yeo7networks'].replace('SalVentAttn', 'VA', inplace=True) atlasinfo['yeo7networks'].replace('Default', 'DMN', inplace=True) atlasinfo['yeo7networks'].replace('SomMot', 'SM', inplace=True) ``` -------------------------------- ### TEXT Keyword Arguments Source: https://github.com/wiheto/netplotbrain/blob/main/docs/api.md Arguments for customizing text elements in the figure. ```APIDOC ## TEXT Keyword Arguments ### Description Arguments for customizing text elements in the figure. ### Arguments - **font** (str) - Font family for all text in the figure. - **fontcolor** (str, list, tuple) - Font color for all text in the figure. - **title_fontsize** (str) - Size of the title font. Default: `medium`. See matplotlib `"fontsize"`. - **titleloc** (str) - Location of the title. Default: `center`. See matplotlib `"loc"`. - **title_weight** (str) - Font weight of the title. Default: `regular`. See matplotlib `"fontweight"`. ``` -------------------------------- ### Spring Layout Subplot with NetworkX Source: https://context7.com/wiheto/netplotbrain/llms.txt Renders a NetworkX spring layout where edge weights influence node proximity. Requires NetworkX and Pandas for data manipulation. Ensure the atlas information is correctly loaded. ```python import netplotbrain import pandas as pd import numpy as np import itertools import templateflow.api as tf atlas = {'template': 'MNI152NLin2009cAsym', 'atlas': 'Schaefer2018', 'desc': '100Parcels7Networks'} atlasinfo = tf.get(extension='.tsv', **atlas) atlasinfo = pd.read_csv(atlasinfo, sep='\t') atlasinfo['network'] = [n.split('_')[2] for n in atlasinfo.name] np.random.seed(2022) edges = np.random.normal(0, 0.025, [100, 100]) for net in atlasinfo['network'].unique(): idx = atlasinfo[atlasinfo['network'] == net].index pairs = np.array(list(itertools.combinations(idx, 2))) edges[pairs[:, 0], pairs[:, 1]] = np.random.normal(0.5, 0.025, len(pairs)) edges[pairs[:, 1], pairs[:, 0]] = edges[pairs[:, 0], pairs[:, 1]] fig, ax = netplotbrain.plot( template='MNI152NLin2009cAsym', nodes=atlas, nodes_df=atlasinfo, edges=edges, view='LSs', # Left, Superior brain views + spring layout template_style='glass', node_color='network', node_scale=20, edge_threshold=0, edge_thresholddirection='>', seed=2022 # reproducible spring layout ) ``` -------------------------------- ### Generating Rotated Sequences with Frames Source: https://github.com/wiheto/netplotbrain/blob/main/docs/tutorial/tutorial2_views.md Create a sequence of rotated images between two views by specifying a two-letter view string (e.g., 'AP') and the number of frames. Images are displayed in a single row. ```python import netplotbrain netplotbrain.plot(template='MNI152NLin2009cAsym', template_style='surface', view=['AP'], frames=5) ``` -------------------------------- ### Control Subplots and Angles with `view` Parameter Source: https://context7.com/wiheto/netplotbrain/llms.txt Demonstrates how the `view` parameter controls which viewing angles are rendered, from single subplots to multi-row grids. ```python import netplotbrain # Multi-angle rows: Left, Superior, Right (top row) + Anterior, Inferior, Posterior (bottom row) fig, ax = netplotbrain.plot( template='MNI152NLin2009cAsym', template_style='surface', view=['LSR', 'AIP'] # list → two rows of subplots ) ``` ```python import netplotbrain # Rotating sequence from Anterior to Posterior in 5 frames fig, ax = netplotbrain.plot( template='MNI152NLin2009cAsym', template_style='surface', view='AP', frames=5 ) ``` ```python import netplotbrain # Full 360° rotation in 8 frames fig, ax = netplotbrain.plot( template='MNI152NLin2009cAsym', template_style='glass', view='360', frames=8 ) ``` -------------------------------- ### Configuring Node Types with `node_type` Source: https://context7.com/wiheto/netplotbrain/llms.txt Describes the different ways nodes can be rendered: 'circles' (2D markers), 'spheres' (3D volumetric), and 'parcels' (filled atlas regions). ```APIDOC ## netplotbrain.plot with `node_type` parameter ### Description Specifies the rendering style for nodes in the visualization. Options include 'circles' for 2D markers, 'spheres' for 3D volumetric representations, and 'parcels' for rendering atlas regions as filled 3D areas. ### Method `netplotbrain.plot` ### Parameters #### Path Parameters None explicitly mentioned. #### Query Parameters None explicitly mentioned. #### Request Body None explicitly mentioned. ### Request Example ```python import netplotbrain import matplotlib.pyplot as plt # fig = plt.figure() # Circles # ax = fig.add_subplot(131, projection='3d') # netplotbrain.plot( # nodes={'atlas': 'Schaefer2018', 'desc': '100Parcels7Networks', 'resolution': 1}, # template='MNI152NLin6Asym', # template_style='glass', # view='S', # node_type='circles', # node_scale=40, # fig=fig, ax=ax # ) # Spheres # ax = fig.add_subplot(132, projection='3d') # netplotbrain.plot( # nodes={'atlas': 'Schaefer2018', 'desc': '100Parcels7Networks', 'resolution': 1}, # template='MNI152NLin6Asym', # template_style='glass', # view='S', # node_type='spheres', # fig=fig, ax=ax # ) # Parcels (renders atlas as filled 3D regions) # ax = fig.add_subplot(133, projection='3d') # netplotbrain.plot( # nodes={'atlas': 'Schaefer2018', 'desc': '100Parcels7Networks', 'resolution': 1}, # template='MNI152NLin6Asym', # template_style=None, # view='S', # node_type='parcels', # node_color='tab20c', # fig=fig, ax=ax # ) ``` ### Response #### Success Response (200) Returns a matplotlib figure and axes object with the specified node types rendered. #### Response Example ```json { "figure": "matplotlib.figure.Figure", "axes": "matplotlib.axes.Axes" } ``` ``` -------------------------------- ### Plot nodes and connectivity matrix Source: https://github.com/wiheto/netplotbrain/blob/main/docs/gallery/plot_connectivitymatrix.ipynb Generates a brain visualization with nodes colored by network and displays the connectivity matrix. Nodes are organized by network color by default, but this can be customized with `cm_order`. ```python # Nodes in connectivity will automatically be organized by node_color, unless cm_order is specified. netplotbrain.plot(nodes={'template': 'MNI152NLin2009cAsym', 'atlas': atlas, 'desc': atlas_desc, 'resolution': 1}, view='LSc', node_type='parcels', nodes_df=atlas_df, node_color='network', node_cmap='Set2') ``` -------------------------------- ### Further Increase Voxel Size for Faster Rendering Source: https://github.com/wiheto/netplotbrain/blob/main/docs/tutorial/tutorial1_input.ipynb Further increase 'template_voxelsize' to 7 for even faster rendering of the 'filled' template style. Note that excessive increases can degrade spatial resolution. ```python # further increasing voxelsize netplotbrain.plot( template='MNI152NLin6Asym', template_style='filled', template_voxelsize=7, arrowaxis=None) # renders in ca. 3 seconds ``` -------------------------------- ### Plot Nodes with a Custom Colormap Source: https://github.com/wiheto/netplotbrain/blob/main/docs/gallery/node_cmap.ipynb Visualizes the nodes using the custom colormap defined previously. This allows for precise control over the colors assigned to each network. ```python # Plot with a the custom colormap netplotbrain.plot(nodes=nodes, node_type='parcels', nodes_df=atlas_df, node_color='network', node_cmap=node_cmap) ``` -------------------------------- ### Plot with Default Filled Template Style Source: https://github.com/wiheto/netplotbrain/blob/main/docs/tutorial/tutorial1_input.ipynb Use the 'filled' template style with default voxel size. Be aware that this can lead to long rendering times. ```python # Call netplotbrain to plot netplotbrain.plot( template='MNI152NLin6Asym', template_style='filled', arrowaxis=None) # renders in ca 156 seconds ``` -------------------------------- ### Visualize NBS Results Source: https://github.com/wiheto/netplotbrain/blob/main/docs/gallery/nbs.ipynb Visualize the mean connectivity matrices for both groups and the significant clusters identified by the NBS analysis. Use appropriate colormaps and titles to clearly present the findings. ```python fig, ax = plt.subplots(1, 3) ax[0].imshow(np.mean(g1, axis=-1), cmap='RdBu_r', vmin=-0.5, vmax=0.5) ax[0].set_title('Group 1 (mean)') ax[1].imshow(np.mean(g2, axis=-1), cmap='RdBu_r', vmin=-0.5, vmax=0.5) ax[1].set_title('Group 2 (mean)') ax[2].imshow(adj, cmap='binary') ax[2].set_title('Significant Clusters') ``` -------------------------------- ### Display Connectivity Matrix Source: https://github.com/wiheto/netplotbrain/blob/main/docs/gallery/spring_layout.ipynb Displays the generated connectivity matrix as an image using Matplotlib. ```python # Show what the connectivity matrix looks like fig, ax = plt.subplots(1) ax.imshow(edges) ``` -------------------------------- ### Plotting with Edge Thresholding Source: https://context7.com/wiheto/netplotbrain/llms.txt Demonstrates how to plot brain networks with specific edge thresholds applied. This is useful for highlighting significant connections. ```APIDOC ## netplotbrain.plot with edge thresholding ### Description Plots brain network data, allowing for the filtering of edges based on their weight. This function is suitable for visualizing sparse or thresholded connectivity matrices. ### Method `netplotbrain.plot` ### Parameters #### Path Parameters None explicitly mentioned. #### Query Parameters None explicitly mentioned. #### Request Body None explicitly mentioned. ### Request Example ```python import netplotbrain import numpy as np import pandas as pd # Assuming nodes_df is a pandas DataFrame with node information # np.random.seed(42) # adj = np.random.uniform(0, 1, (len(nodes_df), len(nodes_df))) # adj = (adj + adj.T) / 2 # np.fill_diagonal(adj, 0) # fig, ax = netplotbrain.plot( # template='MNI152NLin2009cAsym', # nodes=nodes_df, # edges=adj, # edge_threshold=0.7, # edge_thresholddirection='above', # view='L' # ) ``` ### Response #### Success Response (200) Returns a matplotlib figure and axes object containing the plotted brain network. #### Response Example ```json { "figure": "matplotlib.figure.Figure", "axes": "matplotlib.axes.Axes" } ``` ``` -------------------------------- ### Load atlas information from TSV file Source: https://github.com/wiheto/netplotbrain/blob/main/docs/gallery/plot_connectivitymatrix.ipynb Retrieves the atlas definition file using templateflow and loads it into a pandas DataFrame. This file contains node names, colors, and other relevant information. ```python # Get and load the tsv file (information about the atlas) atlas_path = tf.get(atlas=atlas, template=template, desc=atlas_desc, extension='.tsv') atlas_df = pd.read_csv(atlas_path, sep='\t') atlas_df.head() ``` -------------------------------- ### Display DataFrame Head Source: https://github.com/wiheto/netplotbrain/blob/main/docs/gallery/specifying_node_color.ipynb Displays the first few rows of the updated atlas DataFrame, showing the newly added 'network' and 'centrality' columns. ```python # Lets have a look at the data frame now with three different columns for colours atlas_df.head() ``` -------------------------------- ### Optimize Filled Template Rendering with Increased Voxel Size Source: https://github.com/wiheto/netplotbrain/blob/main/docs/tutorial/tutorial1_input.ipynb Increase 'template_voxelsize' to 3 to notably reduce rendering speed for the 'filled' template style. This offers a balance between speed and resolution. ```python netplotbrain.plot( template='MNI152NLin6Asym', template_style='filled', template_voxelsize=3, arrowaxis=None) renders in ca 24 seconds ``` -------------------------------- ### Node input — TemplateFlow atlas dictionary Source: https://context7.com/wiheto/netplotbrain/llms.txt Specifies nodes by referencing a TemplateFlow atlas. The library automatically downloads the specified atlas NIfTI image. ```APIDOC ## Node input — TemplateFlow atlas dictionary ### Description Nodes can be sourced directly from any atlas on templateflow.org by passing a dictionary of TemplateFlow key-value pairs. The atlas NIfTI is downloaded automatically. ### Parameters - **nodes** (Dict[str, Any]) - A dictionary specifying the TemplateFlow atlas. Must include keys like 'template', 'atlas', 'desc', 'resolution'. - **template** (str) - The brain template to use (e.g., 'MNI152NLin2009cAsym'). - **node_type** (str) - Set to 'parcels' to render atlas regions as 3D shapes. - **view** (str) - Specifies the viewing angle (e.g., 'S' for Superior view). - **arrowaxis** (Optional[str]) - Controls directional arrows. Set to None to disable. ### Request Example ```python import netplotbrain # Specify a TemplateFlow atlas as nodes nodes = { 'template': 'MNI152NLin2009cAsym', 'atlas': 'Schaefer2018', 'desc': '400Parcels7Networks', 'resolution': 1 } fig, ax = netplotbrain.plot( template='MNI152NLin2009cAsym', nodes=nodes, node_type='parcels', # render atlas parcels as 3D regions instead of circles view='S', # Superior view arrowaxis=None ) ``` ```