Repository navigation
feat(drawing): add missing connection styles in draw_networkx_edge_labels and display - #8108
Conversation
I added it as a precaution thinking that some higher level assertion already exists. Try removing the assertion altogether and try values -0.1, 1.1 and see if all works as expected. |
|
I meant the check on the length of |
db8b14e to
c54b012
Compare
That is adaptation to You can check those classes in By the way, maybe renaming
If extrapolation works, then I don't think a warning is needed. So I say either restrict it at higher level or leave it as it is without errors or warnings if it works well. |
|
It doesn't seem to always work, from playing with it. I can't seem to find a situation where |
|
Yes, it wasn't correctly picking it up. 3 edits above fix it if that is preferred. |
Co-authored-by: dgpb <[email protected]>
Co-authored-by: dgpb <[email protected]>
c54b012 to
bc07ba9
Compare
|
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. |
Doesn't feel like it at all. Happy to be of help. And thank you for doing this! |
|
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, |
|
@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 networkx/networkx/drawing/nx_pylab.py Lines 720 to 744 in f32dd40 networkx/networkx/drawing/nx_pylab.py Lines 2388 to 2428 in f32dd40 If that's what you mean, I can definitely make those changes! |
|
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 |
|
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 |
|
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 |
a5c7035 to
5a31d44
Compare
The reason why the class is not in the main module in the first place is because it inherits from 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
left a comment
There was a problem hiding this comment.
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?
I think I have covered all of them. Angle has 2 possibilities:
Arc has 3:
We are interested in 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 |
6068767 to
3c050af
Compare
rossbar
left a comment
There was a problem hiding this comment.
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 !
If that is needed and someone is willing, then I think this contains big part of components and logic for some generic solution:
Thanks everyone! Was a pleasure. (As always is in this repo.) |
|
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. |
There is a discrepancy between 2 classes in 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 CurvedArrowTextBaseclass 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 And add the following in place of both classes: class CurvedArrowText(CurvedArrowTextBase, mpl.text.Text):
passThis is pretty much it. Tested it and all seems to be ok. |
Co-authored-by: dgpb <[email protected]>
|
I was actually referring to what Matt said about moving from the 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 :) |
"arc" and "angle" connection styles in draw_networkx_edge_labelsdraw_networkx_edge_labels and display
| class CurvedArrowText(CurvedArrowTextBase, mpl.text.Text): | ||
| pass |
There was a problem hiding this comment.
Can we just inherit from mpl.text.Text in CurvedArrowTextBase to avoid having to define new classes inside the functions?
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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!
Fixes #8106.
This contains the suggested fix by @dg-pb in #8106 to allow
"arc"and"angle"indraw_networkx_edge_labels. I'm not sure theAssertionErrorfor invalidposis 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: