[Matplotlib-devel] New Axes.lines interface

vincent.adrien at gmail.com vincent.adrien at gmail.com
Wed Feb 23 05:06:11 EST 2022


Hello Gregor,

I am not that much familiar with the very last updates of Matplotlib but it looks like the `ax.lines.clear()` method might be worth a try. The following snippet of code might achieve the kind of behavior that you are looking for (if I understood your needs correctly):

```python
import matplotlib.pyplot as plt

def replace_line(ax, xs, ys, **kwargs):
     # Former method:
     # there was already a line drawn
     #if ax.lines:
     #    ax.lines = []
     # New method:
     ax.lines.clear()
     # (re-)draw
     ax.plot(xs, ys, **kwargs)
     
     return ax
     
if __name__ == "__main__":
     plt.ion()
     
     fig, ax = plt.subplots(num="test", clear=True, layout="constrained")

     # Initial line
     xs0 = [0, 1]
     ys0 = [0, 1]
     ax.plot(xs0, ys0, color="tab:red")
     
     # New line that should replace the previous one(s)
     xs1 = [1, 0]
     ys1 = [-1, 2]
     replace_line(ax, xs1, ys1, color="tab:gray")
```

Regards,
Adrien

Le 23/02/2022 à 10:29, Gregor Mönke a écrit :
> Hello,
> 
> I am using interactive matplotlib figures inside a PyQT application (https://github.com/tensionhead/pyboat <https://github.com/tensionhead/pyboat>), and often I want to re-draw lines upon new user input onto an Axis which also has other elements (generated by imshow() in my case). For the last years that basically worked like this:
> 
> def draw():
>      # there was already a line drawn
>      if ax.lines:
>          ax.lines = []
>      # (re-)draw
>      ax.plot(...)
> 
> Now (matplotlib 3.5.1) this does not seem to work anymore, as I get an Attribute error:
> AttributeError: can't set attribute 'lines'
> 
> When I inspect the ax.lines I formerly got a list holding `matplotlib.lines.lines2D` objects, now I have a <Axes.ArtistList of 1 lines>. I looked into the API (https://matplotlib.org/devdocs/api/axes_api.html#other <https://matplotlib.org/devdocs/api/axes_api.html#other>), and what I got from there is that this is a transitional class and I should use this 'as it was a tuple already`. I am stuck here now, I tried to `del` the whole ax.lines attribute or setting it to an empty tuple but nothing worked.
> 
> How can I remove a line from an axis without clearing it? Thanks for your help!
> 
> Best,
> Gregor
> 
> _______________________________________________
> Matplotlib-devel mailing list
> Matplotlib-devel at python.org
> https://mail.python.org/mailman/listinfo/matplotlib-devel



More information about the Matplotlib-devel mailing list