【问题标题】:Move Artist from one Axes to Another on the Same Figure在同一图形上将艺术家从一个轴移动到另一个轴
【发布时间】:2017-07-11 23:45:40
【问题描述】:

我正在尝试将一些数据绘制到子图上,然后当用户选择它时将部分数据移动到同一图中的另一个子图上。我可以从一个轴上移除艺术家并在另一个轴上重新绘制它,但这似乎太慢了。相反,我只想将艺术家从一个轴移动到另一个轴。

我可以轻松地将艺术家从轴上移除,但添加到另一个似乎没有任何作用。 相关代码:

artist.remove()
artist.axes = self.ax1
self.ax1.add_line(artist)
self.fig.canvas.draw_idle()

此代码运行后,所选艺术家不再位于第一个轴上,但不会显示在第二个轴上。更具体地说,艺术家在轴上(ax2.children 中多了一个元素,artist.axes 现在等于 ax2),但即使重绘所有内容,它也不会在视觉上显示出来。

这是一个演示该问题的完整工作示例:

import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
fig = plt.figure(figsize=(10,10))
ax1 = fig.add_subplot(121, picker=True)
ax2 = fig.add_subplot(122, picker=True)

v = [0,1,2,3,4]

plt.ion()

ax1.plot(v, picker=5)

def onclick(event):
    artist = event.artist
    print(artist)
    if isinstance(artist, Line2D):
        artist.remove()
        artist.axes = ax2
        ax2.add_line(artist)
        fig.canvas.draw()


fig.canvas.mpl_connect('pick_event', onclick)

plt.show()

input('...')

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    您还需要更改艺术家的transform 及其axes 属性。

    所以,让你的onclick 函数:

    def onclick(event):
        artist = event.artist
        print(artist)
        if isinstance(artist, Line2D):
            artist.remove()
            artist.axes = ax2
            artist.set_transform(ax2.transData)  # <-- I added this line
            ax2.add_line(artist)
            fig.canvas.draw()
    

    一切正常。

    请注意,您可能还需要更改 ax2 的坐标轴限制,例如:

    ax2.set_xlim(ax1.get_xlim())
    ax2.set_ylim(ax1.get_ylim())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-15
      • 1970-01-01
      • 1970-01-01
      • 2018-07-06
      • 1970-01-01
      相关资源
      最近更新 更多