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

2024-03-29 09:53:12 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

如果我能用一个特殊的函数

AddPoint(ax, new_point, color)

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


Tags: 数据函数newdata颜色图表绘制blue
3条回答

假设你已经有一个绘图,你可以创建这个函数。

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

要添加新颜色的新数据,确实再次调用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()

enter image description here

现在还不清楚为什么不能按照@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()

它允许您向现有的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)

enter image description here

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

相关问题 更多 >