Skip to content

New draw API - #7589

Merged
dschult merged 42 commits into
networkx:mainfrom
mjschwenne:new-draw-api
May 4, 2025
Merged

dschult merged 42 commits into
networkx:mainfrom
mjschwenne:new-draw-api

Conversation

@mjschwenne

Copy link
Copy Markdown
Contributor

The first version of the new draw API is ready! It takes the approach that a graph should be able to describe what it looks like and how it should be visualized. As such, most of the data is read from the graph itself. However, to provide the most convenience and flexibility to the user, they can pass in None to force the visualization to fall back onto the default value or for most attributes if they specify a single value which isn't an attribute name (i.e. node_size=500) that value will be used for all applicable nodes and edges.

I've also included a helper function called apply_matplotlib_colors which takes a color map and generates a new attribute on the graph which stores RGBA tuples. The idea here is to setup the visualization API for dispatching in the future.

The next steps include refactoring the tests to use the new API and setting a deprecation policy for the old one. Below are some examples using the new draw function, currently called new_draw. These examples are what I used while developing the functionality to test, but are otherwise pretty arbitrary.

import networkx as nx
import matplotlib as mpl
import matplotlib.pyplot as plt
import random
from collections import Counter
import numpy as np

G = nx.karate_club_graph()

node_shapes = 'so^>v<dph8'
nx.set_node_attributes(G, {n : random.choice(node_shapes) for n in G.nodes()}, name="shape")

nx.new_draw(G)

image

nx.set_node_attributes(G, {n : 1 / (n + 1) for n in G.nodes()}, name="alpha")
nx.set_node_attributes(G, {n : n for n in G.nodes()}, name="border_width")
nx.new_draw(G)

image

nx.new_draw(G, node_alpha=None)

image

H = nx.karate_club_graph()
nx.set_node_attributes(H, {n : n for n in G.nodes()}, "weight")

nx.apply_matplotlib_colors(H, "weight", "color", mpl.colormaps['plasma'])
nx.new_draw(H, node_label=None)

image

nx.set_node_attributes(H, "#1f78b480", "transparent_color")
nx.new_draw(H, node_color="transparent_color", node_label=False)

The edges in this one are still drawn behind the nodes, but the nodes themselves are transparent, which is why we can still the edges. While this behavior is probably not desirable, it is consistent with the existing visualization capabilities.

image

nx.new_draw(H, node_size=500)

image

I = nx.karate_club_graph()
nx.set_edge_attributes(I, {(u, v): "-|>" if (u + v) % 2 else "-" for u, v in I.edges()}, "arrowstyle")
nx.new_draw(I, arrowsize=10)

image

sl = nx.complete_graph(3, create_using=nx.DiGraph)
sl.add_edge(0, 0)
pos = nx.circular_layout(sl)
nx.set_node_attributes(sl, pos, name="pos")
sl.add_edge(1, 1, style=":")
sl.add_edge(2, 2, style=":")
nx.new_draw(sl)

image

import itertools as it
nodes = "ABC"
prod = list(it.product(nodes, repeat=2)) * 4
M = nx.MultiDiGraph()
for i, (u, v) in enumerate(prod):
    M.add_edge(u, v, w=round(i / 3, 2))

This is what the multigraph looks like with the existing draw API:

connectionstyle = [f"arc3,rad={r}" for r in it.accumulate([0.15] * 4)]
nx.draw(M, connectionstyle=connectionstyle)

image

Here is the same graph with the new API. This time I also added edge labels and colors. I was interested in seeing if I could replicate the old behavior of passing in a list with less entries than the number of edges and iterate over it multiple times. Fortunately the cycle function from itertools makes this easy.

csi = it.cycle(connectionstyle)
nx.set_edge_attributes(M, {e: next(csi) for e in M.edges(keys=True)}, "curve")
nx.set_edge_attributes(M, {tuple(e) : {"label": w, "bbox": {"alpha": 0}} for *e, w in M.edges(keys=True,data="w")}, "label")
nx.apply_matplotlib_colors(M, "w", "color", mpl.colormaps["inferno"], nodes=False)
nx.new_draw(M)

image

@mjschwenne mjschwenne added Visualization Related to graph visualization or layout type: API labels Aug 4, 2024
@mjschwenne

Copy link
Copy Markdown
Contributor Author

The test failures seem to be related to a windows matplotlib import error. The snippet of code in the doc test passes when I run them on my linux machine and when I manually run them. I don't actually have access to a windows computer, so I'm not really able to run the test locally in any way...

UNEXPECTED EXCEPTION: ImportError('DLL load failed while importing _c_internal_utils: The specified module could not be found.')
Traceback (most recent call last):
  File "C:\hostedtoolcache\windows\Python\3.11.9\x64\Lib\doctest.py", line 1355, in __run
    exec(compile(example.source, filename, "single",
  File "<doctest networkx.drawing.layout.spiral_layout[2]>", line 1, in <module>
  File "D:\a\networkx\networkx\networkx\drawing\nx_pylab.py", line 1027, in draw
    import matplotlib.pyplot as plt
  File "C:\hostedtoolcache\windows\Python\3.11.9\x64\Lib\site-packages\matplotlib\__init__.py", line 159, in <module>
    from . import _api, _version, cbook, _docstring, rcsetup
  File "C:\hostedtoolcache\windows\Python\3.11.9\x64\Lib\site-packages\matplotlib\cbook.py", line 32, in <module>
    from matplotlib import _api, _c_internal_utils
ImportError: DLL load failed while importing _c_internal_utils: The specified module could not be found.
D:\a\networkx\networkx\networkx\drawing\layout.py:985: UnexpectedException

@mjschwenne

mjschwenne commented Aug 9, 2024 •

Copy link
Copy Markdown
Contributor Author

As discussed at the last NX community meeting, here is a comparison between a few of the old gallery examples and how you would create the same image with the new draw API. Applying the position data to the graph will be easier after #7571.

House with Colors

Original

G = nx.house_graph()
# explicitly set positions
fig, ax = plt.subplots()
pos = {0: (0, 0), 1: (1, 0), 2: (0, 1), 3: (1, 1), 4: (0.5, 2.0)}

# Plot nodes with different properties for the "wall" and "roof" nodes
nx.draw_networkx_nodes(
    G,
    pos,
    node_size=3000,
    nodelist=[0, 1, 2, 3],
    node_color="tab:blue",
)
nx.draw_networkx_nodes(
    G, pos, node_size=2000, nodelist=[4], node_color="tab:orange"
)
nx.draw_networkx_edges(G, pos, alpha=0.5, width=6)
# Customize axes
ax.margins(0.11)
plt.tight_layout()
plt.axis("off")

image

New

G = nx.house_graph()
fig, ax = plt.subplots()
nx.set_node_attributes(
    G, {0: (0, 0), 1: (1, 0), 2: (0, 1), 3: (1, 1), 4: (0.5, 2.0)}, "pos"
)
nx.set_node_attributes(
    G,
    {
        n: {
            "size": 3000 if n != 4 else 2000,
            "color": "tab:blue" if n != 4 else "tab:orange",
        }
        for n in G.nodes()
    },
)
nx.new_draw(
    G,
    pos="pos",
    edge_alpha=0.5,
    edge_width=6,
    node_label=None,
    node_border_color="k",
)
ax.margins(0.17)
plt.tight_layout()
plt.axis("off")

image

Labels and Colors

Original

G = nx.cubical_graph()
pos = nx.spring_layout(G, seed=3113794652)  # positions for all nodes

# nodes
options = {"edgecolors": "tab:gray", "node_size": 800, "alpha": 0.9}
nx.draw_networkx_nodes(G, pos, nodelist=[0, 1, 2, 3], node_color="tab:red", **options)
nx.draw_networkx_nodes(G, pos, nodelist=[4, 5, 6, 7], node_color="tab:blue", **options)

# edges
nx.draw_networkx_edges(G, pos, width=1.0, alpha=0.5)
nx.draw_networkx_edges(
    G,
    pos,
    edgelist=[(0, 1), (1, 2), (2, 3), (3, 0)],
    width=8,
    alpha=0.5,
    edge_color="tab:red",
)
nx.draw_networkx_edges(
    G,
    pos,
    edgelist=[(4, 5), (5, 6), (6, 7), (7, 4)],
    width=8,
    alpha=0.5,
    edge_color="tab:blue",
)


# some math labels
labels = {}
labels[0] = r"$a$"
labels[1] = r"$b$"
labels[2] = r"$c$"
labels[3] = r"$d$"
labels[4] = r"$\alpha$"
labels[5] = r"$\beta$"
labels[6] = r"$\gamma$"
labels[7] = r"$\delta$"
nx.draw_networkx_labels(G, pos, labels, font_size=22, font_color="whitesmoke")

plt.tight_layout()
plt.axis("off")
plt.show()

image

New

Notice that we can still use multiple calls to the new_draw just like the old API. Even though there is only one function now, by passing node_visible=False it will behave like draw_networkx_edges.

G = nx.cubical_graph()
pos = nx.spring_layout(G, seed=3113794652)  # positions for all nodes
nx.set_node_attributes(G, pos, "pos")  # Will not be needed after PR 7571
labels = iter(
    [
        r"$a$",
        r"$b$",
        r"$c$",
        r"$d$",
        r"$\alpha$",
        r"$\beta$",
        r"$\gamma$",
        r"$\delta$",
    ]
)
nx.set_node_attributes(
    G,
    {
        n: {
            "size": 800,
            "alpha": 0.9,
            "color": "tab:red" if n < 4 else "tab:blue",
            "label": {"label": next(labels), "size": 22, "color": "whitesmoke"},
        }
        for n in G.nodes()
    },
)

nx.new_draw(G, pos="pos", edge_color="tab:grey")

edgelist = [(0, 1), (1, 2), (2, 3), (0, 3)]
nx.set_edge_attributes(
    G,
    {
        (u, v): {
            "width": 8,
            "alpha": 0.5,
            "color": "tab:red",
            "visible": (u, v) in edgelist,
        }
        for u, v in G.edges()
    },
)
nx.new_draw(G, pos="pos", node_visible=False)
edgelist = [(4, 5), (5, 6), (6, 7), (4, 7)]
nx.set_edge_attributes(
    G,
    {
        (u, v): {
            "color": "tab:blue",
            "visible": (u, v) in edgelist,
        }
        for u, v in G.edges()
    },
)
nx.new_draw(G, pos="pos", node_visible=False)

plt.tight_layout()
plt.axis("off")
plt.show()

image

Shortest Path

Original

# Create a graph with nodes and edges
G = nx.Graph()
G.add_nodes_from(["A", "B", "C", "D", "E", "F", "G", "H"])
G.add_edge("A", "B", weight=4)
G.add_edge("A", "H", weight=8)
G.add_edge("B", "C", weight=8)
G.add_edge("B", "H", weight=11)
G.add_edge("C", "D", weight=7)
G.add_edge("C", "F", weight=4)
G.add_edge("C", "I", weight=2)
G.add_edge("D", "E", weight=9)
G.add_edge("D", "F", weight=14)
G.add_edge("E", "F", weight=10)
G.add_edge("F", "G", weight=2)
G.add_edge("G", "H", weight=1)
G.add_edge("G", "I", weight=6)
G.add_edge("H", "I", weight=7)

# Find the shortest path from node A to node E
path = nx.shortest_path(G, "A", "E", weight="weight")
print(path)

# Create a list of edges in the shortest path
path_edges = list(zip(path, path[1:]))

# Create a list of all edges, and assign colors based on whether they are in the shortest path or not
edge_colors = [
    "red" if edge in path_edges or tuple(reversed(edge)) in path_edges else "black"
    for edge in G.edges()
]

# Visualize the graph
pos = nx.spring_layout(G, seed=37)
nx.draw_networkx_nodes(G, pos)
nx.draw_networkx_edges(G, pos, edge_color=edge_colors)
nx.draw_networkx_labels(G, pos)
nx.draw_networkx_edge_labels(
    G, pos, edge_labels={(u, v): d["weight"] for u, v, d in G.edges(data=True)}
)

plt.show()

image

New

For brevity, assume that we have the same graph, as well as path and path_edges as the original code.

nx.set_node_attributes(G, nx.spring_layout(G, seed=37), "pos")
nx.set_edge_attributes(
    G,
    {
        (u, v): {
            "color": (
                "red"
                if (u, v) in path_edges or tuple(reversed((u, v))) in path_edges
                else "black"
            ),
            "label": {"label": d["weight"], "rotate": False},
        }
        for u, v, d in G.edges(data=True)
    },
)
nx.new_draw(G)
plt.tight_layout()
plt.axis("off")

image

@mjschwenne
mjschwenne marked this pull request as ready for review August 14, 2024 15:19

@dschult dschult left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is just a bunch of minor doc/comment wrapping, rewording and 2 varname changes (avoiding the single-letter "l" variable name.

Push back on anything you don't like here...

Comment thread networkx/drawing/nx_pylab.py Resolved
Comment thread networkx/drawing/nx_pylab.py Resolved
Comment thread networkx/drawing/nx_pylab.py Resolved
Comment thread networkx/drawing/nx_pylab.py Resolved
Comment thread networkx/drawing/nx_pylab.py Resolved
Comment thread networkx/drawing/nx_pylab.py Resolved
Comment thread networkx/drawing/nx_pylab.py Resolved
Comment thread networkx/drawing/nx_pylab.py Resolved
Comment thread networkx/drawing/nx_pylab.py Resolved
Comment thread networkx/drawing/nx_pylab.py Resolved
@mjschwenne mjschwenne added this to the 3.4 milestone Aug 22, 2024
@jarrodmillman jarrodmillman modified the milestones: 3.4, 3.5 Oct 10, 2024
@mjschwenne

Copy link
Copy Markdown
Contributor Author

So I was able to correct some of the issues with attributes, in a way that makes me wonder how the rest of the pipelines were passing. Either way, there are still a few tests failing with runtime errors about functions returning a numpy scalar that I'm sure what's up with that but it definitely seems to be dispatch related.

@eriknw

eriknw commented Mar 14, 2025 •

Copy link
Copy Markdown
Contributor

The dispatch CI test is failing because apply_matplotlib_colors creates tuples of numpy scalars, which gets checked (and raised) downstream by get_edge_attributes.

edit: to fix this, update so that functions don't create outputs with numpy scalars.

@eriknw

eriknw commented Mar 14, 2025

Copy link
Copy Markdown
Contributor

Okay, I fixed it by changing apply_matplotlib_colors to not create tuples of numpy scalars.

@mjschwenne

Copy link
Copy Markdown
Contributor Author

Thanks, I was about to do that myself!

@rossbar rossbar left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As discussed (many times, due to my own intransigence) in the community meetings, this PR adds a new visualization API to visualize graphs based on visualization properties stored on the graph. This pattern is akin to other approaches to graph visualization e.g. pygraphviz, where the visualization properties are attributes on the graph itself rather than passed in as parameters to visualization functions.

I would still like to work towards incorporating some of these ideas and improvements into the existing draw-ing framework, but I haven't had time to do so myself and I don't want to block these nice features (and implementation improvements) from getting into the hands' of users! Therefore I approve adding the display as parallel API, with the understanding that the existing draw API will not be removed!

Many, many thanks to @mjschwenne both for the work here and especially the incredible amount of patience as I forced us to hash and re-hash this so many times!

@dschult dschult left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For some reason I though I had approved this last October -- but it doesn't show up now. It is possible I unapproved it while waiting for a chance to look at new changes -- or maybe I never approved it. :)

Anyway, I think this code is a much needed improvement over the current drawing functions. I believe we can leverage it to simplify the other functions too. But there is already a lot in this PR. We can do more after this is in place.

Thanks @mjschwenne !!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

type: API Visualization Related to graph visualization or layout

Development

Successfully merging this pull request may close these issues.

5 participants