Search code examples
pythonnumpymatplotlibgraph

How to reduce this data from a text file to a line graph (Python)


I have data in a .txt file (the file is called numbers.txt) that I'd like to display graphically (line graph). The contents of the file are something like

6 8 2 4 8 // 1 6 8 9 3 // 1 6 8 5 6 // 3 5 6 8 9 //

where // represents a new row.

What I would like to do is write some code that would take a column, for example the first (6 ,1 ,1 ,3) and display it on a line graph. So this graph would have the coordinates (1, 6), (2, 1), (3, 1), (4, 3).

I'm new to python, so I can imagine this is basic stuff. Any help would be appreciated.

Thank you


Solution

  • What about something like this?

    with open('numbers.txt') as f:             # read file
        data = [list(map(int, S.split()))      # numbers as integers
                for s in f.read().split(' //') # from split string
                if (S:=s.strip())]             # walrus operator python ≥ 3.8
    
    
    import matplotlib.pyplot as plt
    
    # create axes
    ax = plt.subplot() 
    
    # set up X values
    xs = list(range(1, len(data)+1))
    
    # plot each line
    for i, ys in enumerate(zip(*data), start=1):
        ax.plot(xs, ys, label=f'line_{i}')
    ax.legend()
    

    output:

    enter image description here