【问题标题】:Updating the position of a ConnectionPatch in matplotlib在 matplotlib 中更新 ConnectionPatch 的位置
【发布时间】:2025-11-21 08:25:02
【问题描述】:

我在 PyQt4 GUI 应用程序中使用 matplotlib 小部件。在图中,我使用 ConnectionPatches 来绘制线条。我保留对它们的引用:

self.x_axis1 = ConnectionPatch((0, yPos), (xPos-boxWidth/2, yPos), coordsA='data', edgecolor='w', linewidth=linewidth)
self.x_axis2 = ConnectionPatch((xPos+boxWidth/2, yPos), (cursorX, yPos), coordsA='data', edgecolor='w', linewidth=linewidth)
self.y_axis1 = ConnectionPatch((xPos, 0), (xPos, yPos-boxHeight/2), coordsA='data', edgecolor='w', linewidth=linewidth)
self.y_axis2 = ConnectionPatch((xPos, yPos+boxHeight/2), (xPos, cursorY), coordsA='data', edgecolor='w', linewidth=linewidth)

...并以典型方式将它们添加到图中:

self.ui.mpl_right.axes.add_patch(self.x_axis1)
self.ui.mpl_right.axes.add_patch(self.x_axis2)
self.ui.mpl_right.axes.add_patch(self.y_axis1)
self.ui.mpl_right.axes.add_patch(self.y_axis2)

根据 matplotlib 文档,您可以这样设置它们的位置:

self.x_axis1.set_positions((0, yPos), (xPos-boxWidth/2, yPos))
self.x_axis2.set_positions((xPos+boxWidth/2, yPos), (cursorX, yPos))
self.y_axis1.set_positions((xPos, 0), (xPos, yPos-boxHeight/2))
self.y_axis2.set_positions((xPos, yPos+boxHeight/2), (xPos, cursorY))

通常,您只需像这样在图形的画布上调用 draw() 来获取要更新的对象:

self.ui.mpl_right.figure.canvas.draw()

...但这完全没有任何作用。

目前,我只是删除它们并使用 remove() 重新添加它们:

self.x_axis1.remove()
self.x_axis2.remove()
self.y_axis1.remove()
self.y_axis2.remove()

有什么方法可以更新 ConnectionPatch 的位置,而不必完全销毁它们并重新添加它们?

【问题讨论】:

  • 我也对这个问题的答案感兴趣。

标签: python matplotlib pyqt4


【解决方案1】:

诀窍是使用 'xy1' 和 'xy2' 属性,而不是像您一样使用 'set_positions()'。所以,如果你把:

self.x_axis1.xy1 = (0, yPos)
self.x_axis1.xy2 = (xPos-boxWidth/2, yPos)

代替:

self.x_axis1.set_positions((0, yPos), (xPos-boxWidth/2, yPos))

它应该可以工作。

【讨论】: