Delete line from matplotlib.pyplot

Two of many ways to do this:

  • delete all lines
  • delete one line using the line instance

Delete all lines

Import needed modules (numpy is only used to generate data):

Generate dummy data and plot:

Creates this plot:

Get current instance of current axes:

Loop through all lines and delete them:

You may think that this could be written as:

but this will not work as the iterable is being changed by the loop itself.

A full listing with pauses to allow visualizing the lines being deleted:

import matplotlib.pyplot as plt
import numpy as np

# plot lines
plt.plot(np.arange(0,10,1), 'g--o')
plt.plot(np.arange(0,20,2), 'r--o')
plt.plot(np.arange(0,30,3), 'b--o')

# get current instance of axes
ax = plt.gca()

for x in range(len(ax.lines)):
    plt.pause(1)
    print(ax.lines[0],'\n')
    # remove line
    ax.lines.remove(ax.lines[0])
    # redraw figure
    plt.draw()

The addition of plt.draw() is required to redraw the plot after each line is removed.

Delete one line using the line instance

import matplotlib.pyplot as plt
import numpy as np

line1, = plt.plot(np.arange(0,10,1), 'b--s')
line2, = plt.plot(np.arange(0,20,2), 'ro')
line3, = plt.plot(np.arange(0,30,3), 'bo')

ax = plt.gca()

ax.lines.remove(line1)

In this case, each plot returns the Line2D instance of the line that can be used to delete the line.

Leave a comment

Design a site like this with WordPress.com
Get started