从图中移除误差条和线条
我想把三个图保存到一个文件里。第一个文件里要包含所有三个图,第二个文件里只要两个,第三个文件里只放一个图。我的想法是这样的:
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")
现在,这样做是没问题的。不过,我想使用误差条(errorbars)。所以我试了试:
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")
现在线条还是被去掉了,但误差条却保留了。我搞不清楚怎么才能把误差条的所有部分都去掉。有没有人能帮我一下?
1 个回答
2
ax.errorbar
会返回三样东西:
- 绘图线(就是你的数据点)
- 帽线(误差条的顶端部分)
- 条线(显示误差条的线)
如果你想要完全“删除”一个图形,就需要把这三样东西都去掉。
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")
要注意的是,你需要遍历第二和第三个参数,因为它们实际上是对象的列表。