简体   繁体   English

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

[英]Add points to the existing matplotlib scatter plot

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 我不需要任何动画

It's unclear why creating a second scatter , as suggested by @b-fg, is not acceptable, but you could write a function like so: 目前尚不清楚为什么不接受按@ b-fg的建议创建第二个scatter ,但是可以编写如下函数:

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

which allows you to add a new point to an existing PathCollection . 它允许您向现有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)

在此处输入图片说明

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... 认识到这一点很重要facecolors阵列中的PathCollection并不一定有相同数量的元素点的数量的,所以如果你尝试,因为一旦加几个点有趣的事情可以用颜色发生,或者如果原始点所有相同的颜色,等等...

Assuming you already have a plot, you can create this function. 假设您已经有一个图,则可以创建此函数。

def AddPoint(plot, x, y, color):
    plot.scatter(x, y, c=color)
    plot.clf()
    plot.show()

To just add a new data with new colour, indeed calling again scatter will add the new points with the specified colour: 要仅添加具有新颜色的新数据,实际上再次调用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()

在此处输入图片说明

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

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