matplotlib-label-lines
matplotlib-label-lines copied to clipboard
ValueError if lines contain single elements
So this is probably a niche case but when this code is presented with a 'line' comprised of a singular point _update_anchors() throws a value error as it can't surround itself with valid line segment points. In this case it'd probably make more sense to set xa, xb ya & yb to the position of the point itself. The rest of the code still works fine with this change and the label appears normally.
I changed the code to the following, the index is unnecessary but I kept it for readability.
# Find the first line segment surrounding x
for i, (xa, xb) in enumerate(zip(xdata[:-1], xdata[1:])):
if min(xa, xb) <= x <= max(xa, xb):
ya, yb = ydata[i], ydata[i + 1]
break
else:
i = 0
ya, yb = ydata[i], ydata[i]
xa, xb = xdata[i], xdata[i]
# raise ValueError("x label location is outside data range!")
The code still throws a warning about the anchor position but it still completes fine, there might be a more intelligent way to handle this though.
I'm not sure this code is correct, won't xdata[1:] raise an exception if its length is 0?
You're correct that'd throw an error, I think with how the rest of the code works if xdata was zero then there wouldn't be a line in the first place. It's been a while since I encountered this issue and so I can't 100% remember why this fix worked, but you could certainly check the length of the xdata first and raise an exception too.