Home > Software design >  How to reduce this data from a text file to a line graph (Python)
How to reduce this data from a text file to a line graph (Python)

Time:04-05

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

CodePudding user response:

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

CodePudding user response:

Alternatively, using pandas:

# Read the file and store it into an array
file1 = open('numbers.txt', 'r')
Lines = file1.readlines()
 
data = []

for line in Lines:
    x = [int(x) for x in line.strip().split(" ") if x.isdigit()]
    data.append(x)

import pandas as pd

#make a dataframe out of the array
df = pd.DataFrame(data)

import matplotlib.pyplot as plt

#plot the first column

df[0].plot()
plt.show()

Reading a file is a good exercice if you're a beginner. You can skip that part though and write right away the following

import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv('numbers.txt', sep=" ", header=None)
   
df[0].plot() # df.plot() to plot all the dataframe
plt.legend()
plt.show()
  • Related