将点添加到现有的matplotlib散点图 [英] Add points to the existing matplotlib scatter plot

查看:138
本文介绍了将点添加到现有的matplotlib散点图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How to add points to the existing diagram? The straightforward solution is to plot a new scatter, adding new data.

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

想要添加更多具有新颜色的点,存在一个问题:我们必须考虑所有先前添加的点。

But if we want to add more points with new colors, there is a problem: we have to take into consideration all previously added points.

如果我可以使用特殊功能,例如

It would be great if I could use a special function like

AddPoint(ax, new_point, color)

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

I want only add new points in new colors. I do NOT need any animations

推荐答案

目前尚不清楚为什么要创建第二个散点,如@ b-fg所示,是不可接受的,但是您可以编写如下函数:

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()

,它允许您向现有 PathCollection 添加新点。

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

示例:

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)

请注意,我提出的功能非常基础,根据使用情况,需要使其更加智能。重要的是要认识到 PathCollection 中的 facecolors 数组不一定具有与数字相同的元素数点数,因此如果您尝试一次添加多个点数,或者原始点数都是相同的颜色,等等,则颜色可能会发生有趣的事情。

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...

这篇关于将点添加到现有的matplotlib散点图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆