Eulalia
Eulalia

Reputation: 35

Remove errorbars and lines from figure

I would like to save three plots to a file. In the first file all three plots should be contained, in the second only two and in the third one only one plot. My idea would be the following:

import matplotlib.pyplot as plt
line1 = plt.plot([1,2,3],[1,2,3])
line2 = plt.plot([1,2,3],[1,6,18])
line3 = plt.plot([1,2,3],[1,1,2])
fig.savefig("testplot1.png")
line1[0].remove()
fig.savefig("testplot2.png")
line2[0].remove()
fig.savefig("testplot3.png")

Now, this works just fine. The problem is that I want to use errorbars. So I tried:

import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
line1=ax.errorbar([1,2,3],[1,2,3],yerr=[0.2,0.2,0.2])
line2=ax.errorbar([1,2,3],[1,6,18],yerr=[0.2,0.2,0.2])
line3=ax.errorbar([1,2,3],[1,1,2],yerr=[0.2,0.2,0.2])
fig.savefig("testplot1.png")
line1[0].remove()
fig.savefig("testplot2.png")
line2[0].remove()
fig.savefig("testplot3.png")

Now the lines are still removed, but the errorbars remain. I can't figure out how to remove all parts of the errorbar. Can somebody help me here?

Upvotes: 2

Views: 2177

Answers (1)

Ffisegydd
Ffisegydd

Reputation: 53698

ax.errorbar returns three things:

  • The plot line (your data points)
  • The cap lines (the caps of the error bars)
  • The bar lines (the bar lines showing the error bars)

You need to remove them all to completely "delete" a plot

import matplotlib.pyplot as plt

fig = plt.figure()

ax = fig.add_subplot(111)

line1=ax.errorbar([1,2,3],[1,2,3],yerr=[0.2,0.2,0.2])
line2=ax.errorbar([1,2,3],[1,6,18],yerr=[0.2,0.2,0.2])
line3=ax.errorbar([1,2,3],[1,1,2],yerr=[0.2,0.2,0.2])

fig.savefig("testplot1.png")

line1[0].remove()
for line in line1[1]:
    line.remove()
for line in line1[2]:
    line.remove()

fig.savefig("testplot2.png")

line2[0].remove()
for line in line2[1]:
    line.remove()
for line in line2[2]:
    line.remove()

fig.savefig("testplot3.png")

Note that you have to iterate over the 2nd and 3rd arguments because they're actually lists of objects.

Upvotes: 2

Related Questions