在Python 2.7中在函数级别导入pylab的首选方法是什么?

时间:2016-02-17 17:30:19

标签: python python-2.7 matplotlib

我在python中编写了一个相对简单的函数,可以用来绘制数据集的时域历史以及快速傅里叶变换后数据集的频域响应。在这个函数中,我使用命令from pylab import *来引入所有必要的功能。然而,尽管成功创建了情节,但我收到了警告

  

import *仅允许在模块级别。

因此,如果使用命令from pylab import *不是首选方法,那么如何从pylab正确加载所有必需的功能。代码附在下面。此外,有没有办法在退出函数后关闭图形,我已经尝试了plt.close()这个子图无法识别?

def Time_Domain_Plot(Directory,Title,X_Label,Y_Label,X_Data,Y_Data):
    # Directory: The path length to the directory where the output file is 
    #            to be stored
    # Title:     The name of the output plot, which should end with .eps or .png
    # X_Label:   The X axis label
    # Y_Label:   The Y axis label
    # X_Data:    X axis data points (usually time at which Yaxis data was acquired
    # Y_Data:    Y axis data points, usually amplitude

    from pylab import *
    from matplotlib import rcParams
    rcParams.update({'figure.autolayout': True})
    Output_Location = Directory.rstrip() + Title.rstrip()
    fig,plt = plt.subplots()
    matplotlib.rc('xtick',labelsize=18)
    matplotlib.rc('ytick',labelsize=18)
    plt.set_xlabel(X_Label,fontsize=18)
    plt.set_ylabel(Y_Label,fontsize=18)
    plt.plot(X_Data,Y_Data,color='red')
    fig.savefig(Output_Location)
    plt.clear()

1 个答案:

答案 0 :(得分:5)

来自matplotlib documentation

  

pylab是一个便利模块,可以在单个名称空间中批量导入matplotlib.pyplot(用于绘图)和numpy(用于数学和使用数组)。虽然许多示例使用pylab,但不再推荐使用。

我建议不要导入pylab,而是尝试使用

import matplotlib
import matplotlib.pyplot as plt

然后使用pyplot为所有plt个功能添加前缀。

我还注意到您将plt.subplots()的第二个返回值分配给plt。您应该将该变量重命名为fft_plot(用于快速傅里叶变换),以避免与pyplot发生命名冲突。

关于您的其他问题(关于fig, save fig()),您需要首先放弃fig,因为没有必要,并且您会打电话savefig() plt.savefig(),因为它是pyplot模块中的一个函数。这条线看起来像

plt.savefig(Output_Location)

尝试这样的事情:

def Time_Domain_Plot(Directory,Title,X_Label,Y_Label,X_Data,Y_Data):
    # Directory: The path length to the directory where the output file is 
    #            to be stored
    # Title:     The name of the output plot, which should end with .eps or .png
    # X_Label:   The X axis label
    # Y_Label:   The Y axis label
    # X_Data:    X axis data points (usually time at which Yaxis data was acquired
    # Y_Data:    Y axis data points, usually amplitude

    import matplotlib
    from matplotlib import rcParams, pyplot as plt

    rcParams.update({'figure.autolayout': True})
    Output_Location = Directory.rstrip() + Title.rstrip()
    fig,fft_plot = plt.subplots()
    matplotlib.rc('xtick',labelsize=18)
    matplotlib.rc('ytick',labelsize=18)
    fft_plot.set_xlabel(X_Label,fontsize=18)
    fft_plot.set_ylabel(Y_Label,fontsize=18)
    plt.plot(X_Data,Y_Data,color='red')
    plt.savefig(Output_Location)
    plt.close()