在for循环中使用matplotlib进行绘图并存储每个绘图的鼠标单击位置

时间:2018-11-28 17:02:56

标签: python-3.x matplotlib jupyter-notebook

我正在编写代码,以将鼠标单击位置存储在for循环中显示的绘图上。显示绘图后,jupyter中的matplotlib笔记本通过将光标悬停在绘图上来显示x和y位置。然后,用户单击该图以选择要存储的感兴趣的x和y。

为了实现以上描述,我编写了以下代码。

import numpy as np
from IPython import display
from IPython.display import clear_output
plt.close("all")
colour=['blue','red','green','black','magenta']
for num in range(len(df_save)):
    listed=[]
    for car,models in cars.items():
        import matplotlib.pyplot as plt
        %matplotlib notebook
        fig = plt.figure()
        ax = fig.add_subplot(111)
        i=0
        for model in models.items():
            ax.plot(df_car[car+model][(df_car[car+model+'_Vel']<=df_save['VEL_MAX'][num]) & (df_car[car+model+'_Vel']>=df_save['VEL_MIN'][num])],
                df_car['emission'][(df_car[car+model+'_Vel']<=df_save['VEL_MAX'][num]) & (df_car[car+model+'_Vel']>=df_save['VEL_MIN'][num])],color=colour[i])
            ax.set_ylim(-0.15,1.25)
            ax.set_title(car,fontsize=20,family='serif', color='black')
            i=i+1
        plt.show()
        ques=input('Do you want to store components for this? ')
        if ques=='Y':
            ques1=input('Enter the number of components: ')
            coords = []
            def onclick(event):
                global ix, iy
                ix, iy = event.xdata, event.ydata
                print ('x = %f, y = %f'%(ix, iy))
                global coords
                coords.append(ix, iy)
                if len(coords) == ques1:
                    fig.canvas.mpl_disconnect(cid)
                return coords
            cid=fig.canvas.mpl_connect('button_press_event', onclick)

            df_save['COMPONENTS'][num]=coords
        else:
            continue

问题

运行程序时,图不包含任何数据,如seen here。我想知道这里出了什么问题,以及有助于实现目标的解决方案。

1 个答案:

答案 0 :(得分:0)

在mpl_connect之后移动plt.show(),并在达到所需的组件数量后关闭图形即可完成操作。我添加了一些调试语句来帮助遵循代码流。

       plt.close("all")
       colour = ['blue', 'red', 'green', 'black', 'magenta']
       for num in range(len(df_car)):

           print '\n--------------\n'
           print 'Current Entry: '+str(num)
           print '\n--------------\n'
           print df_car.loc[num]
           print '\n\n'

           coords = defaultdict(list)

           for car, models in car.items():
               fig = plt.figure()
               ax = fig.add_subplot(111)
               i = 0

               for model in models.items():
                   ax.plot(spec[car+model[0]+'_Vel'][(spec[car+model[0]+'_Vel'] <= df_car['VEL_MAX'][num]) & (spec[car+model[0]+'_Vel'] >= df_car['VEL_MIN'][num])],
                           spec['FLUX'][(spec[car+model[0]+'_Vel'] <= df_car['VEL_MAX'][num]) & (spec[car+model[0]+'_Vel'] >= df_car['VEL_MIN'][num])], color=colour[i])
                   ax.set_ylim(-0.15, 1.25)
                   ax.set_title(car+'_'+str(num), fontsize=20,
                                family='serif', color='black')
                   i = i+1

               print '\n--------------\n'
               print 'car: ' + car
               print '\n--------------\n'

               ques = raw_input('Do you want to store components for above car? ')

               if ques == 'y' or ques == 'Y':
                   ques1 = input('Enter the number of components: ')

                   def onclick(event):
                       global ix, iy
                       ix, iy = event.xdata, event.ydata
                       print ('x = %d, y = %d' % (ix, iy))
                       coords[car].append((ix, iy))
                       if len(coords[car]) == ques1:
                           fig.canvas.mpl_disconnect(cid)
                           plt.close(fig)
                       return coords

                   cid = fig.canvas.mpl_connect('button_press_event', onclick)
                   plt.draw()
                   plt.show()
               else:
                   continue

           df_car['COMPONENTS'][num] = coords
           print '\n--------------\n'
           print 'Updated Entry:::'
           print '\n--------------\n'
           print df_car.loc[num]
           print '\n'
           plt.close('all')