Plotting#

CORNETO supports plotting of graphs through different backends, such as Graphviz, Pydot, and NetworkX

import corneto as cn

cn.info()
Installed version:v1.0.0.dev39+1266a7d
Available backends:CVXPY v1.6.6, PICOS v2.6.1
Default backend (corneto.opt):CVXPY
Installed solvers:CVXOPT, GLPK, GLPK_MI, HIGHS, SCIP, SCIPY
Graphviz version:v0.20.3
Installed path:/home/runner/work/corneto/corneto/corneto
Repository:https://github.com/saezlab/corneto

Using graphviz#

If graphviz and dot are installed, e.g. via conda install python-graphviz, you can use the plot method to visualize the graphs

from corneto.graph import Graph

G = Graph()
G.add_edge(1, 2)
G.add_edge(2, 3)
G.add_edge(1, 3)
G.plot()
../../_images/b26ad1cae5f801af9f1f8987fd50baf9d02e13ca30bb919b1953c71386255646.svg
# This returns a graphviz object
digraph = G.to_graphviz()
type(digraph)
graphviz.graphs.Digraph
str(digraph)
'digraph {\n\tnode [fixedsize=true]\n\t1 [shape=circle]\n\t2 [shape=circle]\n\t1 -> 2 [arrowhead=normal]\n\t2 [shape=circle]\n\t3 [shape=circle]\n\t2 -> 3 [arrowhead=normal]\n\t1 [shape=circle]\n\t3 [shape=circle]\n\t1 -> 3 [arrowhead=normal]\n}\n'
G.plot_values(edge_values=[-1, 1, 1])
../../_images/57d11cef1bfdf549eb5f3ad7f89af176d7cc4ca1e4123c50f0f474bb5f08e64e.svg
G.plot_values(edge_values=[-1, 1, 1], edge_indexes=[0, 1])
../../_images/695b675bbed64769795a5d4b5679f497a98ea53de0131017b1f088e057155cc7.svg

Using Pydot#

from IPython.display import SVG, display

G_pydot = G.to_dot(backend="pydot")
display(SVG(G_pydot.create_svg()))
../../_images/24e1ec3456aac414ead7e1d2a0132bca5e4cf7d7906abec983423b0bf388c670.svg

Using NetworkX with Pydot#

import matplotlib.pyplot as plt
import networkx as nx
from networkx.drawing.nx_pydot import from_pydot, graphviz_layout

# Convert pydot to networkx
G_nx = from_pydot(G.to_dot(backend="pydot"))

# Use Graphviz layout (e.g. 'dot' for hierarchies, 'neato' for general layout)
pos = graphviz_layout(G_nx, prog="neato")  # 'neato', 'dot', 'fdp', etc.

# Plot with styling
plt.figure(figsize=(3, 3))
nx.draw(
    G_nx,
    pos,
    with_labels=True,
    arrows=True,
    node_color="lightblue",
    edge_color="gray",
    node_size=500,
    font_size=14,
)
plt.show()
../../_images/9609ba0afa0d7e388e1a3b19e01965a1e2c69d0a51422cdc032d98e0f0d36a7f.png