2016-11-16 70 views
0

我目前正试图在我的代码中实现“缩放”功能。我的意思是我希望并排放置两个子图,其中一个包含初始数据,另一个包含由用户输入决定的“放大”图。用用户输入更新存在的Matplotlib子图

目前,我可以并排创建两个子图,但在调用用户输入之后,而不是更新第二个子图,我的脚本正在创建一个全新的图,下面没有更新第二个子图。首先绘制包含data的图表非常重要,以便用户可以相应地选择输入的值。

def plot_func(data): 

    plot_this = data 

    plt.close('all') 

    fig = plt.figure() 

    #Subplot 1 
    ax1 = fig.add_subplot(1,2,1) 
    ax1.plot(plot_this) 
    plt.show() 

    zoom = input("Where would you like to zoom to:) 
    zoom_in = plot_this[0:int(zoom)] 

    #Subplot 2 
    ax2 = fig.add_subplot(1,2,2) 
    ax2.plot(zoom_in) 

    plt.show() 

上面的代码是什么,我希望做的简化版本。显示一个子图,并基于该子图,让用户输入一个输入。然后编辑已经创建的子图或者创建一个与第一个相邻的新图。同样重要的是,'放大'的小节与第一个反对的下边并排。

+0

您是否知道已经有了(http://matplotlib.org/users/navigation_toolbar.html)来实现通常的matplotlib绘制窗口中的[缩放工具]? – ImportanceOfBeingErnest

+0

我没有!感谢您的链接。尽管我并没有试图实际放大,而是试图绘制与自身平行的更大数据集的一部分。也许缩放是不正确的词。 – neerbasu

+0

所以,也许你正在寻找[这样的事情](http://gtk3-matplotlib-cookbook.readthedocs.io/en/latest/zooming.html)? – ImportanceOfBeingErnest

回答

0

我认为用户输入数字进行缩放并不是很方便。更为标准的方式是由各种matplotlib tools提供的鼠标交互。

有用于在不同的情节变焦没有标准的工具,但是我们可以很容易地提供与显示在下面的代码使用matplotlib.widgets.RectangleSelector此功能。

我们需要在两个子图中绘制相同的数据,并将RectangleSelector连接到其中一个子图(ax)。每次进行选择时,第一个子图中的选择的数据坐标都被简单地用作第二个子图的轴限制,有效地证明放大(或放大)功能。

import matplotlib.pyplot as plt 
import numpy as np 
from matplotlib.widgets import RectangleSelector 


def onselect(eclick, erelease): 
    #http://matplotlib.org/api/widgets_api.html 
    xlim = np.sort(np.array([erelease.xdata,eclick.xdata ])) 
    ylim = np.sort(np.array([erelease.ydata,eclick.ydata ])) 
    ax2.set_xlim(xlim) 
    ax2.set_ylim(ylim) 

def toggle_selector(event): 
    # press escape to return to non-zoomed plot 
    if event.key in ['escape'] and toggle_selector.RS.active: 
     ax2.set_xlim(ax.get_xlim()) 
     ax2.set_ylim(ax.get_ylim()) 


x = np.arange(100)/(100.)*7.*np.pi 
y = np.sin(x)**2 

fig = plt.figure() 
ax = fig.add_subplot(121) 
ax2 = fig.add_subplot(122) 

#plot identical data in both axes 
ax.plot(x,y, lw=2) 
ax.plot([5,14,21],[.3,.6,.1], marker="s", color="red", ls="none") 
ax2.plot(x,y, lw=2) 
ax2.plot([5,14,21],[.3,.6,.1], marker="s", color="red", ls="none") 

ax.set_title("Select region with your mouse.\nPress escape to deactivate zoom") 
ax2.set_title("Zoomed Plot") 

toggle_selector.RS = RectangleSelector(ax, onselect, drawtype='box', interactive=True) 
fig.canvas.mpl_connect('key_press_event', toggle_selector) 

plt.show() 

enter image description here

+0

这是一个了不起的工具,谢谢你!我测试了它,它完美地工作。我确实有一个问题,那就是我正在Jupyter Notebook中运行我的脚本,这就是为什么我对用户输入法感兴趣的原因。是否有可能在笔记本电脑中允许此功能? – neerbasu

+0

@neerbasu事实上,你想使用jupyter笔记本是应该在问题中添加的重要信息。我从来没有使用jupyter,但是不是关于笔记本的全部故事,用户可以直接输入任何值,直接输入代码?为什么你需要'输入'呢?我也怀疑我的上面的互动示例在jupyter中不起作用。 – ImportanceOfBeingErnest

+0

你是对的,我很抱歉,在看到它是一个关键因素之前我没有提到它。我很抱歉。好消息是,我确实发现了一些代码,可以使用与前面提到的相同的功能。 – neerbasu

0
%matplotlib inline 
import mpld3 
mpld3.enable_notebook() 
+1

你需要提供一些最低限度的信息,这3条线对于你的问题的答案有多远。有人如何来到这个网站根本不明白这些线的意思和把它们放在哪里。 – ImportanceOfBeingErnest