Get the shown limits of the line in a matplotlib plot?

Viewed 74

Say I have this simple matplotlib plot:

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()
x_data = [0, 1.0]
y_data = [0, 1.0]
myline = ax.plot(x_data, y_data)

def on_keypress(event):
  if event.key == 'ctrl+p':
    print("Printing myline: {}".format(myline))

fig.canvas.mpl_connect('key_press_event', on_keypress)

plt.show()

Say, I run this, and I make a "Zoom to rectangle":

plot image full

... and thus, I get this zoomed region shown:

plot image zoomed

How can I find the coordinates of the endpoints of the shown segment of the line?

In the example code, a line is printed when I press CTRL+p - and when I hit that, I'd like the coordinates of the shown segment of the line to be printed, regardless of which segment is shown (if whole line is shown, then (0,0), (1,1) would be expected endpoints printed).

How can I do that? Of course, I'd like the method to work for an arbitrary line, not just the (0,0), (1,1) one ...

1 Answers

Here is an approach using shapely:

from shapely.geometry import LineString, box
import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()
x_data = [0.7, 1.0]
y_data = [2.1, 3.4]
myline, = ax.plot(x_data, y_data)

def on_keypress(event):
  if event.key == 'ctrl+p':
    viewlim = ax.viewLim   
    linestr = LineString(myline.get_xydata())
    viewbox = box(viewlim.x0, viewlim.y0, viewlim.x1, viewlim.y1)    
    inters = viewbox.intersection(linestr)
    coords = np.asarray(inters.coords)
    print(coords)

fig.canvas.mpl_connect('key_press_event', on_keypress)

plt.show()

Sample output: enter image description here

>>>[[0.79071429 2.49309524]
>>>[1.         3.4       ]]

Matplotlib must have something similar internally to calculate clip on parameters; however, I did not immediately find it in the source code.

Related