0

I have this code that graphs any number of datasets from txt files in one graph. It works very well but I am unable to figure out how to show the all file names in the Matplotlib graph legend. I can get the last file that was graphed to show in the legend, but that's all I can get. So how can I get every filename to show in the legend? You could test using the baseline files here at 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()

1 Answers1

0

Produce the legend outside the loop but make sure to actually label your plots.

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()
ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
  • @ Importance no that didn't seem to create a legend –  Apr 19 '17 at 13:24
  • @ Importance all I got was a little empty square on the upper right side of the bottom graph box –  Apr 19 '17 at 13:27
  • I didn't see that you did not actually label your plots at all. Updated the answer. – ImportanceOfBeingErnest Apr 19 '17 at 13:30
  • That worked but what worked best was to place the plt.legend inside the subplot. But ill give you the answer. Thanks! –  Apr 19 '17 at 13:34
  • It works but is kind of bad style since if you have 100 files, you create 100 legends, one replacing the previous. But if it doesn't slow down your plotting, you may sure do it. – ImportanceOfBeingErnest Apr 19 '17 at 13:36
  • Yes that is true but there shouldn't be any more than 10 files being input. Either way the legend shows in the graph area. is there a way to get the legend outside of the graph area? –  Apr 19 '17 at 13:40