在 Matplotlib 中显示来自多个数据集图形的文件名

Showing filenames from graphing of multiple datasets in Matplotlib

我有这段代码可以在一张图中绘制来自 txt 文件的任意数量的数据集。它工作得很好,但我无法弄清楚如何在 Matplotlib 图例中显示所有文件名。我可以获得图例中显示的最后一个文件,但这就是我所能得到的。那么我怎样才能让每个文件名都显示在图例中呢?您可以在 Github https://github.com/thomasawolff/verification_text_data

处使用基准文件进行测试
def graphWriterIRI():
    figsize = plt.figure(figsize=(16,10))
    # Set up the plots
    plt.subplot(2, 1, 1)
    plt.grid(True)
    plt.ylabel('IRI value', fontsize=12)
    #pylab.ylim([0,150])
    plt.title('Right IRI data per mile for verification runs')
    plt.tick_params(axis='both', which='major', labelsize=8)
    plt.hold(True)

    plt.subplot(2, 1, 2)
    plt.grid(True)
    plt.ylabel('IRI value', fontsize=12)
    #pylab.ylim([0,150])
    plt.title('Left IRI data per mile for verification runs:')
    plt.tick_params(axis='both', which='major', labelsize=8)
    plt.hold(True)

    # Iterate over the files in the current directory
    for filename in os.listdir(os.getcwd()):
        # Initialize a new set of lists for each file
        startList = []
        endList = []
        iriRList = []
        iriLList = []
        # Load the file
        if filename.endswith('.TXT'):
            with open(filename, 'rU') as file:
                for row in csv.DictReader(file):
                    try:
                        startList.append(float(row['Start-Mi']))
                        endList.append(float(row['  End-Mi']))
                    except:
                        startList.append(float(row['Start-MP']))
                        endList.append(float(row['  End-MP']))
                    try:
                        iriRList.append(float(row[' IRI R e']))
                        iriLList.append(float(row['IRI LWP ']))
                    except:
                        iriRList.append(float(row[' IRI RWP']))
                        iriLList.append(float(row['IRI LWP ']))
        # Add new data to the plots
        try:
            plt.subplot(2, 1, 1)
            plt.plot(startList,iriRList)
            plt.legend([filename]) # shows the last filename in the legend

            plt.subplot(2, 1, 2)
            plt.plot(startList,iriLList)
            plt.legend([filename])
        except ValueError:pass
    #return iriRList,iriLList

    plt.show()
    plt.close('all')

graphWriterIRI()

在循环外生成图例,但确保实际标记您的图。

def graphWriterIRI():
    ...
    # Iterate over the files in the current directory
    for filename in os.listdir(os.getcwd()):
        ...
        if filename.endswith('.TXT'):
            with open(filename, 'rU') as file:
                for row in csv.DictReader(file):
                    ...
            filenames.append(filename)


        plt.subplot(2, 1, 1)
        plt.plot(startList,iriRList, label=filename)

        plt.subplot(2, 1, 2)
        plt.plot(startList,iriLList, label=filename)


    plt.legend()
    plt.show()