简体   繁体   English

如何从图中删除点?

[英]How to remove points from a plot?

I am using matplotlib.pyplot. 我正在使用matplotlib.pyplot。

I would like to do the following: 我要执行以下操作:

  1. I want to plot a series of background dots (single blue dot in example). 我想绘制一系列背景点(示例中为单个蓝色点)。
  2. I add an additional series of dots (3 black dots in example) 我添加了一系列附加的点(例如3个黑点)
  3. I save the figure 我保存数字
  4. I remove the additional series of dots (black) and keep the background one (blue). 我删除了其他系列的点(黑色),并使背景一个(蓝色)。

How can I perform step 4? 如何执行步骤4? I would like to avoid having to replot the background dots. 我想避免重新绘制背景点。

Hereunder is an example of code with step 4 missing. 以下是缺少第4步的代码示例。

import matplotlib.pyplot as plt

fig = plt.figure()

plt.xlim(-10,10)
plt.ylim(-10,10)

#step 1: background blue dot
plt.plot(0,0,marker='o',color='b')

#step 2: additional black dots
points_list = [(1,2),(3,4),(5,6)]
for point in points_list:
    plt.plot(point[0],point[1],marker='o',color='k')

#step 3: save
plt.savefig('test.eps')

#step 4: remove additional black dots

You can remove the plotted points by doing this : 您可以通过执行以下操作删除绘制的点:

temporaryPoints, = plt.plot(point[0],point[1],marker='o',color='k')
temporaryPoints.remove()

You can use: 您可以使用:

#step 2
black_points, = plt.plot( zip(*points_list), marker="o", color="k")

#... step 3 ...
#...

#step 4
black_points.set_visible( False)

The plot function returns a list of Line2D objects which represent the plotted data. plot函数返回代表绘制数据的Line2D对象的列表。 These objects have a remove method which will remove them from the figure they've been plotted on (note that Line2D inherits from Artist which you can check via Line2D.__mro__ ): 这些对象有一个remove方法,该方法将从绘制它们的图形中将它们删除(请注意Line2D继承自Artist ,可以通过Line2D.__mro__进行检查):

remove() method of matplotlib.lines.Line2D instance
    Remove the artist from the figure if possible.  The effect
    will not be visible until the figure is redrawn, e.g., with
    :meth:`matplotlib.axes.Axes.draw_idle`.  Call
    :meth:`matplotlib.axes.Axes.relim` to update the axes limits
    if desired.

    [...]

So you can do the following (I combined plotting the single points in one go): 因此,您可以执行以下操作(我一次性完成了对单个点的绘制操作):

points = plt.plot(*zip(*points_list), 'o', color='k')[0]
# Remove the points (requires redrawing).
points.remove()

Keeping your for loop this would be: 保持您的for循环为:

points = []
for point in points_list:
    points.extend(
        plt.plot(point[0], point[1], marker='o', color='k')
    )
for p in points:
    p.remove()

Or more concise using a list comprehension: 或更简洁的使用列表理解:

points = [plt.plot(*p, marker='o', color='k')[0] for p in points_list]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM