单击matplotlib散点图点以显示基于点元数据的另一个图形?

2024-04-26 14:48:29 发布

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

我已经让this在我的机器上运行,它给了我一个想法:我可以根据点的元数据显示一个新的图形,而不是打印一个字符串吗

为了了解我的数据,我有一个包含实验名称和结果的SQL表,然后还有一个包含整个实验过程的表。使用matplotlib绘制图形也很容易。我想创建一些交互式的东西,在那里我可以绘制实验的最终结果(某种散点图),使用户可以深入查看整个实验的图表

看起来我应该能够修改on_pick函数来进行绘图,如下代码所示

import matplotlib.pyplot as plt

class custom_objects_to_plot:
    def __init__(self, x, y, name):
        self.x = x
        self.y = y
        self.name = name

a = custom_objects_to_plot(10, 20, "a")
b = custom_objects_to_plot(30, 5, "b")
c = custom_objects_to_plot(40, 30, "c")
d = custom_objects_to_plot(120, 10, "d")

def on_pick(event):
    plt.scatter([1,2,3,4], [5,6,7,8]) # For the real function, run a SQL query to
                                      # get the data needed to do the plot of interest
    plt.title(event)
    plt.show()

fig, ax = plt.subplots()
for obj in [a, b, c, d]:
    artist = ax.plot(obj.x, obj.y, 'ro', picker=5)[0]
    artist.obj = obj

fig.canvas.callbacks.connect('pick_event', on_pick)

plt.show()

当我运行这个时,我得到一个错误:QCoreApplication::exec: The event loop is already running

{}能完成我想做的事情吗

(最终,目标是将这个交互式图形放在panel浏览器窗口中,但我现在只满足于从命令行运行matplotlib。)


Tags: theto数据nameselfeventobj图形
2条回答

我想出了如何绘制新的图形。它所需要的只是图形和轴的on_pick中的唯一名称,而不仅仅是plt

def on_pick(event):
    my_fig, my_ax = plt.subplots() # New plot with unique name
    my_ax.scatter([1, 2, 3, 4], [5, 6, 7, 8]) # Make the scatterplot
    my_fig.show() # Show the plot

你做的一切都很好,除了你不需要创建一个新的散布,而是更新旧的散布。这就是你的错误所在plt.show()的循环已经在运行,在回调中,您正试图再次启动它。您的回调应该如下所示:

def on_pick(event):
    plt.clf()  # It will clear previous scatter from figure
    plt.scatter([1, 2, 3, 4], [5, 6, 7, 8])
    plt.draw()  # It will tell pyplot to redraw

这将导致: Result

答案是提供的,看at this question

相关问题 更多 >