python Matplotlib -如何移除特定直线或曲线

1cklez4t  于 2022-12-10  发布在  Python
关注(0)|答案(5)|浏览(183)

我想删除多行绘图中的一行。下面是一个例子,但对我来说还不够,因为它只删除了最后一行,而不是我想删除的那一行。我该怎么做呢?我该如何在整个程序中处理一行(通过名称、编号、引用)并删除该行?

self.axes.lines.remove(self.axes.lines[0])
zmeyuzjn

zmeyuzjn1#

几乎所有的绘图函数都会返回对artist对象的引用,该对象是通过

ln, = plot(x, y)  # plot actually returns a list of artists, hence the ,
im = imshow(Z)

如果您有引用,则可以通过remove(doc)函数删除艺术家,例如:

ln.remove()
im.remove()
lawou6xi

lawou6xi2#

编辑:塔卡斯韦尔的答案比我的好
我把我的答案无论如何记录在案(因为赞成票很好:眨眼:)
如果不想显式保存所有行的引用,但知道要删除的行的索引,可以利用maptplotlib为您存储这些索引的事实。

self.axes.lines

是一个matplotlib.lines.Line2D的列表。因此,要删除第二条线,您可以

self.axes.lines[1].remove()
h43kikqp

h43kikqp3#

我也有同样的需求,对我来说,在数据序列中添加一个id,然后通过找到具有给定id的序列(集合)来删除它,这样做会更整洁。

def add_series(x, id):
  plt.plot(x, gid = id)

def remove_series(id):
  for c in plt.collections: # possibly better to use: for c in plt.lines (see comment)
    if c.get_gid() == id:
      c.remove()
zsbz8rwp

zsbz8rwp4#

该代码生成欠阻尼二阶系统的阶跃响应。该代码还可用于说明曲线图的叠加。该代码生成并以图形方式显示两个时间常数参数值的响应。该代码还说明了在for循环中创建彗星。

import numpy as np
import matplotlib.pyplot as plt

The following programme runs on version 3.6.
Code generates a pair of lines and the line 2 is removed in a for loop which
simulates a comet effect
pts=100
t2 = np.linspace(0.0,5.0,pts)
t2=(t2/50)
tm=t2*(10**3)
nz=t2.size
tc=np.linspace(0.8,2.5,2)
nz=tc.size
for n in range (nz):
    print(tc[n])
    resp = 1 - np.exp(-tc[n]*tm*10**-3*50) * np.cos(2*np.pi*50*tm*10**-3)
    for m in range(pts):
        plt.xlim(0,100)
        plt.ylim(0,2)
        plt.xlabel('Time,in milliseconds',fontsize=12)
        plt.ylabel('Respose',fontsize=12)
        plt.title('Underdamped Second Order System Step Response',fontsize=14)
        line1,=plt.plot(tm[0:m+1],resp[0:m+1],color='black',linewidth=0.2)
        line2,=plt.plot(tm[m],resp[m],marker='o',color='red',markersize=5)
        ax = plt.gca()
        plt.pause(0.02)
        ax.lines.remove(line2)
        plt.grid('on')
plt.show()
wecizke3

wecizke35#

您也可以将其用于多个子地块

subfig, subax = plt.subplots(3) 

def add_series(x, y0, y1, y2, gid):
    plt.figure(subfig.number)
    ln, = subax[0].plot(x, y0, gid=gid)
    ln, = subax[1].plot(x, y1, gid=gid)
    ln, = subax[2].plot(x, y2, gid=gid)
    plt.draw()

def remove_series(self, gid):
    plt.figure(subfig.number)
    for c0, c1, c2 in zip(subax[0].lines, subax[1].lines, subax[2].lines):
        if c0.get_gid() == gid:
            c0.remove()
        if c1.get_gid() == gid:
            c1.remove()
        if c2.get_gid() == gid:
            c2.remove()
    plt.draw()

相关问题