Skip to content

feat(drawing): add missing connection styles in draw_networkx_edge_labels and display - #8108

Merged
rossbar merged 12 commits into
networkx:mainfrom
Peiffap:enh/add-connection-styles
Jul 24, 2025
Merged

rossbar merged 12 commits into
networkx:mainfrom
Peiffap:enh/add-connection-styles

Conversation

@Peiffap

@Peiffap Peiffap commented Jun 10, 2025

Copy link
Copy Markdown
Member

Fixes #8106.

This contains the suggested fix by @dg-pb in #8106 to allow "arc" and "angle" in draw_networkx_edge_labels. I'm not sure the AssertionError for invalid pos is sufficiently clear. I've also augmented the test introduced in #7739 to check all styles.

On the (slightly modified) example provided in the linked issue, we now get:

import matplotlib.pyplot as plt
import networkx as nx

g = nx.DiGraph()
g.add_edge(1, 2)

pos = nx.spring_layout(g)

nx.draw_networkx_nodes(g, pos)
nx.draw_networkx_labels(g, pos)

edge = (1, 2)

styles = ['arc', 'angle']

for cs in styles:
    nx.draw_networkx_edges(g, pos, edgelist = [edge], connectionstyle = cs)
    nx.draw_networkx_edge_labels(g, pos, edge_labels = {edge: 'edge'}, connectionstyle = cs)

plt.show()

cs

@dg-pb

dg-pb commented Jun 10, 2025

Copy link
Copy Markdown
Contributor

I'm not sure the AssertionError for invalid pos is sufficiently clear.

I added it as a precaution thinking that some higher level assertion already exists.
But it doesn't.
And maybe it shouldn't as values below 0 and above 1 are most likely valid.
They should just extrapolate beyond bounds.

Try removing the assertion altogether and try values -0.1, 1.1 and see if all works as expected.

@Peiffap

Peiffap commented Jun 10, 2025

Copy link
Copy Markdown
Member Author

I meant the check on the length of points, although maybe that's just my lack of familiarity with this part of the codebase showing. I'll play around with values outside of [0, 1] as well and see what happens then. Perhaps a warning makes sense if we're relying on extrapolation?

@Peiffap
Peiffap force-pushed the enh/add-connection-styles branch from db8b14e to c54b012 Compare June 10, 2025 12:36
@dg-pb

dg-pb commented Jun 10, 2025

Copy link
Copy Markdown
Contributor

I meant the check on the length of points

That is adaptation to matplotlib. Given its current state it is exact and IMO unlikely to change.

You can check those classes in import matplotlib.patches - it can be seen very clearly what numbers of vertices are possible for each and what sort of bezier curve it is constructing.

By the way, maybe renaming points to vertices would be a good idea - just to keep variable names consistent.

Perhaps a warning makes sense if we're relying on extrapolation?

If extrapolation works, then I don't think a warning is needed.
If this is allowed and considered a feature then it would be very annoying to get warnings if one decides to make use of it.

So I say either restrict it at higher level or leave it as it is without errors or warnings if it works well.

@Peiffap

Peiffap commented Jun 10, 2025

Copy link
Copy Markdown
Member Author

It doesn't seem to always work, from playing with it. I can't seem to find a situation where t becomes less than 0, but setting label_pos=1.1 with connectionstyle="angle" fails when the else gets removed because there are too many values to unpack on the next line. I suggest we keep the assertion as it was in your code sample, or perhaps someone can dig into that more deeply in a follow-up PR.

Comment thread networkx/drawing/nx_pylab.py Resolved
Comment thread networkx/drawing/nx_pylab.py Resolved
Comment thread networkx/drawing/nx_pylab.py Resolved
@dg-pb

dg-pb commented Jun 10, 2025

Copy link
Copy Markdown
Contributor

Yes, it wasn't correctly picking it up. 3 edits above fix it if that is preferred.

@Peiffap
Peiffap force-pushed the enh/add-connection-styles branch from c54b012 to bc07ba9 Compare June 10, 2025 14:59
@Peiffap

Peiffap commented Jun 10, 2025

Copy link
Copy Markdown
Member Author

Thanks for being patient with me! I'm not very familiar with the drawing functionality so I apologize for the additional burden I'm placing on you. I've added your suggestions to get rid of the assertion, and added tests to ensure it works correctly.
I've also amended the relevant commits to add you as co-author (sorry for skipping this initially, I was in a rush earlier!).

@dg-pb

dg-pb commented Jun 10, 2025 •

Copy link
Copy Markdown
Contributor

I apologize for the additional burden I'm placing on you.

Doesn't feel like it at all. Happy to be of help. And thank you for doing this!

@mjschwenne

Copy link
Copy Markdown
Contributor

We recently introduced a new visualization API in #7589, and it would be much appreciated if any improvements to the old visualization system were also reflected there. Long term, we'd like to shift focus to the new visualization method, display. We will keep the old functions but I'd like to eventually have them be wrappers of display so that we aren't maintaining two separate ways to do the same thing.

@Peiffap

Peiffap commented Jun 12, 2025

Copy link
Copy Markdown
Member Author

@mjschwenne That sounds reasonable. From quickly skimming the relevant code in the draw API, it looks like it was pretty much a copy-paste of the _update_text_pos_angle function in draw_networkx_edge_labels (but without the "bar" connection style, it looks like; I suppose that got added after the draw API went in).

def _update_text_pos_angle(self, arrow):
# Fractional label position
path_disp = self._get_arrow_path_disp(arrow)
(x1, y1), (cx, cy), (x2, y2) = path_disp.vertices
# Text position at a proportion t along the line in display coords
# default is 0.5 so text appears at the halfway point
t = self.label_pos
tt = 1 - t
x = tt**2 * x1 + 2 * t * tt * cx + t**2 * x2
y = tt**2 * y1 + 2 * t * tt * cy + t**2 * y2
if self.labels_horizontal:
# Horizontal text labels
angle = 0
else:
# Labels parallel to curve
change_x = 2 * tt * (cx - x1) + 2 * t * (x2 - cx)
change_y = 2 * tt * (cy - y1) + 2 * t * (y2 - cy)
angle = (np.arctan2(change_y, change_x) / (2 * np.pi)) * 360
# Text is "right way up"
if angle > 90:
angle -= 180
if angle < -90:
angle += 180
(x, y) = self.ax.transData.inverted().transform((x, y))
return x, y, angle

def _update_text_pos_angle(self, arrow):
# Fractional label position
# Text position at a proportion t along the line in display coords
# default is 0.5 so text appears at the halfway point
t = self.label_pos
tt = 1 - t
path_disp = self._get_arrow_path_disp(arrow)
is_bar_style = isinstance(
arrow.get_connectionstyle(), mpl.patches.ConnectionStyle.Bar
)
# 1. Calculate x and y
if is_bar_style:
# Bar Connection Style - straight line
_, (cx1, cy1), (cx2, cy2), _ = path_disp.vertices
x = cx1 * tt + cx2 * t
y = cy1 * tt + cy2 * t
else:
# Arc or Angle type Connection Styles - Bezier curve
(x1, y1), (cx, cy), (x2, y2) = path_disp.vertices
x = tt**2 * x1 + 2 * t * tt * cx + t**2 * x2
y = tt**2 * y1 + 2 * t * tt * cy + t**2 * y2
# 2. Calculate Angle
if self.labels_horizontal:
# Horizontal text labels
angle = 0
else:
# Labels parallel to curve
if is_bar_style:
change_x = (cx2 - cx1) / 2
change_y = (cy2 - cy1) / 2
else:
change_x = 2 * tt * (cx - x1) + 2 * t * (x2 - cx)
change_y = 2 * tt * (cy - y1) + 2 * t * (y2 - cy)
angle = np.arctan2(change_y, change_x) / (2 * np.pi) * 360
# Text is "right way up"
if angle > 90:
angle -= 180
elif angle < -90:
angle += 180
(x, y) = self.ax.transData.inverted().transform((x, y))
return x, y, angle

If that's what you mean, I can definitely make those changes!

@mjschwenne

Copy link
Copy Markdown
Contributor

Yes, a lot of the code was copied directly from the old system regarding the lower level matplotlib code. It should be reasonable simple to copy the changes here up there so that display is capable of going everything that the old draw_* functions.

@dg-pb

dg-pb commented Jun 12, 2025

Copy link
Copy Markdown
Contributor

It would be great to avoid keeping 2 copies of such a thing.

We could place it outside those functions as a base, then Inherit within functions:

class CurvedArrowTextBase:
    # All code here
    ...

def foo():
    class CurvedArrowText(CurvedArrowTextBase, mpl.text.Text)
        pass

def bar():
    class CurvedArrowText(CurvedArrowTextBase, mpl.text.Text)
        pass

@Peiffap

Peiffap commented Jun 13, 2025

Copy link
Copy Markdown
Member Author

I think the duplication is only temporary, so imo it makes more sense to keep it for now and just get rid of the old copy for the draw_* functions whenever they get replaced by wrappers around equivalent display_* functions.

@Peiffap
Peiffap force-pushed the enh/add-connection-styles branch from a5c7035 to 5a31d44 Compare June 13, 2025 13:13
@dg-pb

dg-pb commented Jun 13, 2025

Copy link
Copy Markdown
Contributor

I think the duplication is only temporary, so imo it makes more sense to keep it for now and just get rid of the old copy for the draw_* functions whenever they get replaced by wrappers around equivalent display_* functions.

The reason why the class is not in the main module in the first place is because it inherits from matplotlib class. My best guess is that for this exact reason it was duplicated.

But this can be solved by the above. Can be left for another PR ofc, but I think this is a perfect opportunity to do it.

@rossbar rossbar added the Visualization Related to graph visualization or layout label Jun 20, 2025

@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.

Having read through this and the mpl docs I'm not 100% sure we're covering all the cases; particularly for angle which seems like there are a lot of possibilities in terms of returned tuples.

I wonder if we shouldn't just raise explicitly on angle and say that connectionstyle isn't supported? @dg-pb any opinions?

@dg-pb

dg-pb commented Jun 20, 2025 •

Copy link
Copy Markdown
Contributor

I'm not 100% sure we're covering all the cases

I think I have covered all of them.

Angle has 2 possibilities:

  1. [MOVETO, LINETO, LINETO]
  2. [MOVETO, LINETO, CURVE3, CURVE3, LINETO]

Arc has 3:

  1. [MOVETO, LINETO]
  2. [MOVETO, LINETO, CURVE3, CURVE3, LINETO] (this one has 2 variations, but the treatment of them both is the same)
  3. [MOVETO, LINETO, CURVE3, CURVE3, LINETO, CURVE3, CURVE3, LINETO]

We are interested in [ANY, LINETO], which I think I extract for each case correctly.
These are lines, the rest is edge rounding, which I do not take into account (that would just be extra 100% of complexity for 1% benefit).

Then, all that is left is to identify in which line the requested position resides.


I think this is good to go and with this, ~99% of connection styles are covered (except label adaptation to minuscule curvature of rounded edges).


I would just like to reiterate myself that I think it would be of benefit to factor out CurvedArrowText class as I suggested in #8108 (comment) to avoid unnecessary repetition of pretty hefty code. If not in this PR, then at least promptly after.

Comment thread networkx/drawing/tests/test_pylab.py Resolved
@Peiffap
Peiffap force-pushed the enh/add-connection-styles branch from 6068767 to 3c050af Compare July 9, 2025 21:18
Comment thread networkx/drawing/nx_pylab.py Resolved
Comment thread networkx/drawing/nx_pylab.py Resolved

@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.

This LGTM in so far as I follow it :). Ultimately it'd be great to see if some of this code wouldn't be a nice candidate for upstreaming to matplotlib. I'm sure NX isn't the only library that would benefit from having a method on the FancyArrowPatches that allows users to get the position/angle at an arbitrary distance along the curve!

That's a pie-in-the-sky goal though - for now this looks to me like it will add the missing feature for the addditional connectionstyles and is no more complex than what we already have. Thanks @dg-pb and @Peiffap !

@dg-pb

dg-pb commented Jul 11, 2025

Copy link
Copy Markdown
Contributor

Ultimately it'd be great to see if some of this code wouldn't be a nice candidate for upstreaming to matplotlib.

If that is needed and someone is willing, then I think this contains big part of components and logic for some generic solution:

  1. Segment any path to its constituent components. Currently this is done only for LINETO segments. Would need to incorporate CURVE3 and CURVE4, but that is easy.
  2. Calculate lengths of all of those. Currently this is done only for LINETO. CURVE3 and CURVE4 are missing.
  3. Identify which segment desired point lies in. Logic is there.
  4. Calculate the position and angle on the segment of interest. Logic is there for CURVE3 and LINETO. CURVE4 is missing.


Thanks everyone! Was a pleasure. (As always is in this repo.)

@Peiffap

Peiffap commented Jul 11, 2025

Copy link
Copy Markdown
Member Author

Thanks for your review, @rossbar. I agree with you and @dg-pb that this bit of code seems like it does something other projects might also be interested in reusing. For me personally, that's a bit too far out of my wheelhouse for now, but it's a good idea and the discussion here is a good starting point for anyone looking to work on that.

Outside of the scope of this PR, I also still think that there is value in avoiding the duplicated code with the old and new visualization APIs. Are there any concrete plans for when these changes will happen? Maybe something has been discussed in terms of releases, perhaps this is something to think about doing before 4.0.

@dg-pb

dg-pb commented Jul 11, 2025 •

Copy link
Copy Markdown
Contributor

I also still think that there is value in avoiding the duplicated code with the old and new visualization APIs.

There is a discrepancy between 2 classes in _get_arrow_path_disp method...

I would say it would be good to do this as part of this PR, it is a very simple change and is directly related to what was done here.

Just put this above draw_networkx_edge_labels:

CurvedArrowTextBase
class CurvedArrowTextBase:
    def __init__(
        self,
        arrow,
        *args,
        label_pos=0.5,
        labels_horizontal=False,
        ax=None,
        **kwargs,
    ):
        # Bind to FancyArrowPatch
        self.arrow = arrow
        # how far along the text should be on the curve,
        # 0 is at start, 1 is at end etc.
        self.label_pos = label_pos
        self.labels_horizontal = labels_horizontal
        if ax is None:
            ax = plt.gca()
        self.ax = ax
        self.x, self.y, self.angle = self._update_text_pos_angle(arrow)

        # Create text object
        super().__init__(self.x, self.y, *args, rotation=self.angle, **kwargs)
        # Bind to axis
        self.ax.add_artist(self)

    def _get_arrow_path_disp(self, arrow):
        """
        This is part of FancyArrowPatch._get_path_in_displaycoord
        It omits the second part of the method where path is converted
            to polygon based on width
        The transform is taken from ax, not the object, as the object
            has not been added yet, and doesn't have transform
        """
        dpi_cor = arrow._dpi_cor
        trans_data = self.ax.transData
        if arrow._posA_posB is None:
            raise ValueError(
                "Can only draw labels for fancy arrows with "
                "posA and posB inputs, not custom path"
            )
        posA = arrow._convert_xy_units(arrow._posA_posB[0])
        posB = arrow._convert_xy_units(arrow._posA_posB[1])
        (posA, posB) = trans_data.transform((posA, posB))
        _path = arrow.get_connectionstyle()(
            posA,
            posB,
            patchA=arrow.patchA,
            patchB=arrow.patchB,
            shrinkA=arrow.shrinkA * dpi_cor,
            shrinkB=arrow.shrinkB * dpi_cor,
        )
        # Return is in display coordinates
        return _path

    def _update_text_pos_angle(self, arrow):
        # Fractional label position
        # Text position at a proportion t along the line in display coords
        # default is 0.5 so text appears at the halfway point
        import matplotlib as mpl
        import matplotlib.path
        import numpy as np
        t = self.label_pos
        tt = 1 - t
        path_disp = self._get_arrow_path_disp(arrow)
        conn = arrow.get_connectionstyle()
        # 1. Calculate x and y
        points = path_disp.vertices
        if is_curve := isinstance(
            conn,
            mpl.patches.ConnectionStyle.Angle3 | mpl.patches.ConnectionStyle.Arc3,
        ):
            # Arc3 or Angle3 type Connection Styles - Bezier curve
            (x1, y1), (cx, cy), (x2, y2) = points
            x = tt**2 * x1 + 2 * t * tt * cx + t**2 * x2
            y = tt**2 * y1 + 2 * t * tt * cy + t**2 * y2
        else:
            if not isinstance(
                conn,
                mpl.patches.ConnectionStyle.Angle
                | mpl.patches.ConnectionStyle.Arc
                | mpl.patches.ConnectionStyle.Bar,
            ):
                msg = f"invalid connection style: {type(conn)}"
                raise TypeError(msg)
            # A. Collect lines
            codes = path_disp.codes
            lines = [
                points[i - 1 : i + 1]
                for i in range(1, len(points))
                if codes[i] == mpl.path.Path.LINETO
            ]
            # B. If more than one line, find the right one and position in it
            if (nlines := len(lines)) != 1:
                dists = [math.dist(*line) for line in lines]
                dist_tot = sum(dists)
                cdist = 0
                last_cut = 0
                i_last = nlines - 1
                for i, dist in enumerate(dists):
                    cdist += dist
                    cut = cdist / dist_tot
                    if i == i_last or t < cut:
                        t = (t - last_cut) / (dist / dist_tot)
                        tt = 1 - t
                        lines = [lines[i]]
                        break
                    last_cut = cut
            [[(cx1, cy1), (cx2, cy2)]] = lines
            x = cx1 * tt + cx2 * t
            y = cy1 * tt + cy2 * t

        # 2. Calculate Angle
        if self.labels_horizontal:
            # Horizontal text labels
            angle = 0
        else:
            # Labels parallel to curve
            if is_curve:
                change_x = 2 * tt * (cx - x1) + 2 * t * (x2 - cx)
                change_y = 2 * tt * (cy - y1) + 2 * t * (y2 - cy)
            else:
                change_x = (cx2 - cx1) / 2
                change_y = (cy2 - cy1) / 2
            angle = np.arctan2(change_y, change_x) / (2 * np.pi) * 360
            # Text is "right way up"
            if angle > 90:
                angle -= 180
            elif angle < -90:
                angle += 180
        (x, y) = self.ax.transData.inverted().transform((x, y))
        return x, y, angle

    def draw(self, renderer):
        # recalculate the text position and angle
        self.x, self.y, self.angle = self._update_text_pos_angle(self.arrow)
        self.set_position((self.x, self.y))
        self.set_rotation(self.angle)
        # redraw text
        super().draw(renderer)

Where all that I have done is added internal imports for _update_text_pos_angle method, removed inheritance and appended Base to the name.

And add the following in place of both classes:

class CurvedArrowText(CurvedArrowTextBase, mpl.text.Text):
        pass

This is pretty much it. Tested it and all seems to be ok.

@Peiffap

Peiffap commented Jul 11, 2025

Copy link
Copy Markdown
Member Author

I was actually referring to what Matt said about moving from the draw API to display, but I realize now that wasn't very clear.

Regardless... I'm not sure if what you suggested is the neatest way to do things, but it's a very simple change indeed and a definite step in the right direction, so in it goes! Thanks @dg-pb :)

@Peiffap Peiffap changed the title Implement "arc" and "angle" connection styles in draw_networkx_edge_labels feat(drawing): add missing connection styles in draw_networkx_edge_labels and display Jul 11, 2025
Comment on lines +809 to +810
class CurvedArrowText(CurvedArrowTextBase, mpl.text.Text):
pass

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.

Can we just inherit from mpl.text.Text in CurvedArrowTextBase to avoid having to define new classes inside the functions?

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.

That would mean having matplotlib import at the top of the module. The whole thing of defining classes inside functions was to prevent it and keep things the way they were.

Changing that would be a breaking change.

Just stating the obvious, no idea on whether it is good idea to change it.

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.

Thanks for the clarification - this wasn't immediately obvious to me from the diffs alone. Just wanted to make sure we weren't abstracting for abstraction's sake!

@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.

Thanks @Peiffap @dg-pb and @rossbar
This looks good!

@rossbar
rossbar merged commit 8c4a5f8 into networkx:main Jul 24, 2025
@Peiffap
Peiffap deleted the enh/add-connection-styles branch July 24, 2025 19:16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

type: Enhancements Visualization Related to graph visualization or layout

Development

Successfully merging this pull request may close these issues.

connectionstyle arc and angle not working in draw_networkx_edge_labels

5 participants