==== Front Netw Neurosci Netw Neurosci netn Network Neuroscience 2472-1751 MIT Press One Broadway, 12th Floor, Cambridge, Massachusetts 02142, USA journals-info@mit.edu netn_a_00313 10.1162/netn_a_00313 Research Article NetPlotBrain: A Python package for visualizing networks and brains Fanton Silvia https://orcid.org/0000-0002-0533-6035 Thompson William Hedley * Department of Clinical Neuroscience, Karolinska Institutet, Stockholm, Sweden Department of Applied Information Technology, University of Gothenburg, Gothenburg, Sweden Competing Interests: The authors have declared that no competing interests exist. * Corresponding Author: william.hedley.thompson@gu.se Handling Editor: Andrew Zalesky 2023 30 6 2023 7 2 461477 23 9 2022 02 3 2023 © 2023 Massachusetts Institute of Technology 2023 Massachusetts Institute of Technology https://creativecommons.org/licenses/by/4.0/ This is an open-access article distributed under the terms of the Creative Commons Attribution 4.0 International License, which permits unrestricted use, distribution, and reproduction in any medium, provided the original work is properly cited. For a full description of the license, please visit https://creativecommons.org/licenses/by/4.0/. Abstract Visualizations of networks are complex since they are multidimensional and generally convey large amounts of information. The layout of the visualization can communicate either network properties or spatial properties of the network. Generating such figures to effectively convey information and be accurate can be difficult and time-consuming, and it can require expert knowledge. Here, we introduce NetPlotBrain (short for network plots onto brains), a Python package for Python 3.9+. The package offers several advantages. First, NetPlotBrain provides a high-level interface to easily highlight and customize results of interest. Second, it presents a solution to promote accurate plots through its integration with TemplateFlow. Third, it integrates with other Python software, allowing for easy integration to include networks from NetworkX or implementations of network-based statistics. In sum, NetPlotBrain is a versatile but easy to use package designed to produce high-quality network figures while integrating with open research software for neuroimaging and network theory. Author Summary NetPlotBrain is a Python package to easily create network visualizations on a brain and view brain anatomy. NetPlotBrain is integrated with TemplateFlow and popular Python packages, the former facilitating the selection of the appropriate template or atlas from the available options and the latter providing the user with easy customization and fine-tuning. Network visualizations Python Network neuroscience Research software HORIZON EUROPE Marie Sklodowska-Curie Actions 10.13039/100018694 764860 Fanton Silvia citationFanton, S., & Thompson, W. H. (2023). NetPlotBrain: A Python package for visualizing networks and brains. Network Neuroscience, 7(2), 461–477. https://doi.org/10.1162/netn_a_00313 ==== Body pmcINTRODUCTION Visualizations in science display various types of information, ranging from theoretical models to empirical data (Sargent, 1996). They are critical for effective communication of quantitative information (Cheng et al., 2022; Tufte, 1985; van Wijk, 2006) and for facilitating the learning of scientific information (Nolan & Perrett, 2016; Rom, 2015; Vavra et al., 2011). Visualizations also have a crucial role in exploratory science, which is a central method to learn from data (Behrens, 1997; Fox & Hendler, 2011; Tukey, 1977). One trend within some programmatic visualization tools has aimed to provide users with high-level interfaces. This trend entails that users specify and customize their plot by only pointing to the data, and the visualization tool will then handle the rest. Alternatively, for low-level interfaces, users specify individual aspects of the figure or input each variable independently. Frequently, high-level interfaces are implemented by inputting a data frame (i.e., a table of data with column names). Users then specify different column names for aspects of the figure they would like the visualization tool to manipulate. Examples of high-level user visualization interfaces can be seen in tools such as GGPlot2 for R (Wickham, 2016) and Seaborn for Python (Waskom et al., 2020). Visualizing networks is challenging because the visualization represents complex multidimensional topologies embedded in the network within the two-dimensional media of a static figure. For instance, a commonly used format in network neuroscience involves circular layouts, where all the nodes are placed in a circle. Alternatively, other representations include spring, spectral, or random layouts depending on the choice of node placement algorithm that leverages the network features such as structure. Algorithms for displaying networks in informative ways have become a field itself (see McGuffin, 2012). When the location of the nodes is important, as is often the case with brain networks, nodes are often placed in the coordinate system corresponding to their location (e.g., the brain). There are many tools available today to achieve these different types of visualizations. For visualizing networks in the brain, there is BrainNet Viewer (Xia et al., 2013) and nilearn (Abraham et al., 2014). For general network layouts, there is Cytoscape (Smoot et al., 2011), Gephi (Bastian et al., 2009), NetworkX (Hagberg et al., 2008), Circos (Krzywinski et al., 2009), and igraph (Csárdi & Nepusz, 2006). Additionally, for other types of visualizations of multimodal brain data, there are Brainrender (Claudi et al., 2021), Visbrain (Combrisson et al., 2019), and PySurfer (https://pysurfer.github.io/). All tools have trade-offs regarding their detail, ease of use, and suitability for certain questions and use cases. However, we identified three features that we would like to see within a single tool for brain network visualizations. The tool should do the following:be easy to specify and customize have easy integration with software relating to neuroimaging, but also with more general network software promote the user to plot accurate templates concerning the coordinate system of the nodes While some currently available software attempt to solve these different points to varying degrees, we do not believe any yet sufficiently solves all three. To solve the problem, we developed NetPlotBrain (network plots onto brains), a Python 3.9+ package. It is built on scientific Python libraries, including Matplotlib, pandas, and NumPy, while also being compatible with more specific packages such as NetworkX and other Python implementations of network-based statistics. The high-level interface is built up as a single function with an array to tailor the visualization to one's needs. Finally, it leverages TemplateFlow (Ciric et al., 2022) to provide access to a large and expanding portfolio of brain templates and atlases, with complete provenance and versioning records that ensure accuracy and reproducibility. This article will proceed by introducing how to use different aspects of NetPlotBrain (Thompson et al., 2023; https://github.com/wiheto/netplotbrain). First, we discuss the basic workflow and input of data. Second, we discuss how figures can be customized, including the high-level interface. Third, we show examples of how NetPlotBrain integrates with other software. Finally, the Methods section discusses installation and dependencies. RESULTS Replicating programming patterns of more general-purpose visualization utilities such as Matplotlib, the core function of NetPlotBrain’s user interface is netplotbrain.plot(). A User Interface Optimized for the Visualization of Human and Nonhuman Brain Networks Users specify three different data inputs to display brain networks. These three inputs are (a) the template, which specifies an anatomical image and a 3D coordinate system; (b) the nodes, which specify how the spatial frame established by the template is partitioned to define nodes; and (c) the edges, which give rise to the specific connectivity. Each of these components has a keyword argument that can be passed:fig, ax = netplotbrain.plot(template=…, nodes=…, edges=…). All three arguments are optional (i.e., it is possible to plot a template by itself or just plot the nodes by themselves). If edges are specified, the “nodes” argument must be specified. The two outputs of the function are objects of Matplotlib classes. The first of these objects (fig) is of the Figure class for Matplotlib. The second is a list of Matplotlib 3D axes (Axes3D) for each of the subplots. These outputs allow the users to further specify low-level properties of the plot at will with Matplotlib. However, the users do not need to interact with these outputs, if they do not wish, as they can save the figure directly (as a .png or .svg file) in the NetPlotBrain function using the “savename” keyword argument. The respective input to each of these three arguments can be specified in multiple ways to maximize flexibility. Spatial inputs (i.e., the template and the nodes) can originate locally or be procured by TemplateFlow (Ciric et al., 2022). TemplateFlow is an online repository of MRI atlases and templates that unambiguously names standard neuroimaging spaces and related resources (e.g., templates and atlases). We will discuss each data component and outline how that data can be submitted (see Figure 1). Figure 1.  Summary of the different input formats and file locations for the different NetPlotBrain components. Information regarding templates, nodes, and edges can be provided locally or from TemplateFlow. Each of the three components can be plotted and customized independently. The spatial reference of the visualization—the template. The template shows the brain as a background image for the nodes and edges to be plotted onto. Its function is to help the user see where the different nodes are located in the brain. For different purposes and tastes, some may want a more detailed outline, while others may want just the contours of the brain. Primarily, the template can be specified as a string containing template names of MRI images available on templateflow.org:netplotbrain.plot(template='MNI152NLin2009cAsym'). Conveniently, the TemplateFlow client implements lazy-loading, and the template file will be downloaded only once upon the first use onto the user’s local hard drive. NetPlotBrain will attempt to take the most suitable anatomical image for the requested template. By default, NetPlotBrain seeks a segmented T1w image of the brain. If that file is not present for a template space, then NetPlotBrain takes the binary mask of the segmented brain. Further flexibility and options in template selection (e.g., when the selected template features multiple cohorts) are comprehensively described in the documentation. Alternatively, the template can be any skull-stripped or segmented three-dimensional NIfTI (Neuroimaging Informatics Technology Initiative; Cox et al., 2004) image file stored locally, specified either as a string containing the path in a file system,netplotbrain.plot(template='./path/to/img.nii.gz'), or as a nibabel object,import nibabel as nib … img=nib.load('./path/to/img.nii.gz') netplotbrain.plot(template=img). This alternative template specification allows, for instance, the visualization of networks corresponding to a specific, individual brain or standard spaces defined by templates unavailable within TemplateFlow (e.g., customized, study-wise templates or templates with reuse restrictions that cannot be shared openly). Defining the nodes. Nodes represent the different brain regions. Nodes can be specified as a pandas DataFrame of coordinates, a NIfTI image indicated as a string, a nibabel object stored locally, or a dictionary with key/value pairs of any TemplateFlow atlas available on templateflow.org. When nodes are specified as a pandas DataFrame, node information should be contained in columns 'x', 'y', 'z' or identified using the “node_columnnames” argument:import pandas as pd … node_df = pd.DataFrame(data={'x':               […],                'y':               […],                'z':               […]}) netplotbrain.plot(nodes=nodes_df). The missing input in the 'x', 'y', and 'z' columns consists of lists of coordinates in the respective template space. Additional columns in the pandas DataFrame can be added to contain additional data to be used in the figure (see the High-level interface subsection below). The default column names for coordinates can be changed with the “node_columnnames” keyword argument. Nodes can also be defined by a 3D NIfTI map containing a discrete (i.e., piecewise smooth) partition of the reference brain defined by the template. The partition is discrete because a unique integer label identifies each node. Here, the alternatives are similar to the local template input, where the input is a string that designates a path to a NIfTI file,netplotbrain.plot(nodes='./path/to/img.nii.gz'), or a nibabel object,import nibabel as nib … img         =        nib.load('./path/to/img.nii.gz') netplotbrain.plot(nodes=img). The “nodes” argument can also point to a TemplateFlow atlas. An atlas can be selected by specifying a dictionary of keyword/value options to choose the template. For example, the following arguments in netplotbrain.plot will download the 400 parcel parcellation from the Schaefer2018 atlas (Schaefer et al., 2018) in the MNI152NLin2009cAsym space from TemplateFlow:nodes_tf = {'atlas':    'Schaefer2018',       'desc':    '400Parcels7Networks',       'resolution': 1}. netplotbrain.plot(template='MNI152NLin2009cAsym', nodes=nodes_tf). Connecting the nodes—the edges. Edges specify connections between nodes. Edges can be expressed as either a NumPy array (adjacency matrix) or a pandas DataFrame (edge list). When a NumPy array is used, the array should be N × N in shape, where N denotes the number of nodes. The below code will plot random edges for 100 predefined nodes:import numpy as np … netplotbrain.plot(nodes=nodes,           edges=edges_array), where the edges_array variable contains a 100 × 100 NumPy array. When a pandas DataFrame is used, edge information should be specified in the default columns 'i' and 'j', whereas 'weight' can be an optional column for edge width.import pandas as pd … edges_df = pd.DataFrame(data={'i':              […],                'j':              […],                'weight':            […]}). netplotbrain.plot(nodes=nodes,           edges=edges_df). In edges_df, the node indices are specified as 'i' and 'j', and the connectivity weight is in the optional column 'weight'. Additional columns in the data frame can further customize the figure (see the Network Visualizations Are Highly Customizable section below). The default column names 'i', 'j' can be changed with the “edge_columnnames” keyword argument. The keyword argument “edge_weights” specifies the weight of edges. Combining the three components. The three components are, by definition, interrelated to each other, with nodes being specified in the template space and edges referencing nodes. However, in NetPlotBrain, each component can be specified and customized separately (see Figure 1 for a graphic of how the three components can be specified and how they combine). Note that, if using NetworkX, it is also possible to input the nodes and edges simultaneously using the “network” keyword argument (see Integration With Other Software section below). Network Visualizations Are Highly Customizable The number of options to customize the figures is extensive and will not be presented in full (see the online documentation). Here, we will discuss four main aspects relating to customization: (a) the naming convention of keyword arguments, (b) the display alternatives for templates and nodes, (c) the high-level interface for specifying node or edge properties, and (d) the viewing options. The naming convention of keyword arguments. There are a lot of possible keyword arguments that can be used in NetPlotBrain. Generally, we try to preserve the option name in the software we use, such as Matplotlib (e.g., alpha for transparency). However, since there are multiple components, the keyword arguments follow the following convention: _