将点添加到现有的 matplotlib 散点图

toy*_*nug 11 python plot data-visualization matplotlib scatter-plot

如何向现有图表添加点?直接的解决方案是绘制新的散点图,添加新数据。

ax.scatter(data[:,0], data[:,1], cmap = cmap, c = color_data)
ax.scatter(new_points_x, new_points_y, color='blue')
Run Code Online (Sandbox Code Playgroud)

但是如果我们想用新的颜色添加更多的点,就有一个问题:我们必须考虑所有以前添加的点。

如果我可以使用像这样的特殊功能,那就太好了

AddPoint(ax, new_point, color)
Run Code Online (Sandbox Code Playgroud)

我只想添加新颜色的新点。我不需要任何动画

Diz*_*ahi 7

It's unclear why creating a second scatter, as suggested by @b-fg, is not acceptable, but you could write a function like so:

def addPoint(scat, new_point, c='k'):
    old_off = scat.get_offsets()
    new_off = np.concatenate([old_off,np.array(new_point, ndmin=2)])
    old_c = scat.get_facecolors()
    new_c = np.concatenate([old_c, np.array(matplotlib.colors.to_rgba(c), ndmin=2)])

    scat.set_offsets(new_off)
    scat.set_facecolors(new_c)

    scat.axes.figure.canvas.draw_idle()
Run Code Online (Sandbox Code Playgroud)

which allows you to add a new point to an existing PathCollection.

example:

fig, ax = plt.subplots()
scat = ax.scatter([0,1,2],[3,4,5],cmap=matplotlib.cm.spring, c=[0,2,1])
fig.canvas.draw()  # if running all the code in the same cell, this is required for it to work, not sure why
addPoint(scat, [3,6], 'c')
addPoint(scat, [3.1,6.1], 'pink')
addPoint(scat, [3.2,6.2], 'r')
addPoint(scat, [3.3,6.3], 'xkcd:teal')
ax.set_xlim(-1,4)
ax.set_ylim(2,7)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

Note that the function that I'm proposing is very basic and would need to be made much smarter depending on the use case. It is important to realize that the facecolors array in a PathCollection does not necessarily have the same number of elements as the number of points, so funny things can happen with colors if you try to add several points as once, or if the original points are all the same colors, etc...


b-f*_*-fg 6

要添加具有新颜色的新数据,确实再次调用scatter将添加具有指定颜色的新点:

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(10)
a = np.random.rand(10)
plt.scatter(x, a, c='blue')
b = np.random.rand(10)
plt.scatter(x, b, c='red')
plt.show()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

  • 我有一个 **现有** 情节并想在其上添加一个新点 (2认同)
  • @b-fg 您可能希望将新点附加到现有曲线,而不是每个新点一个新散点,原因有很多。您的解决方案*视觉上*有效,但您以后无法执行任何操作,例如检索数据、将两条曲线添加在一起、更改透明度...如果一条 y(x) 曲线具有唯一的“gid”并且包含所有它的数据。如果你有多个分散的情况,它就会变得不必要的困难。 (2认同)