Reading arrays from txt file in python to plot a graph

77 Views Asked by At

I'm new to python and want to plot a graph using data stored in arrays on a txt file...

content in the txt file ar just the arrays... nothing else.. exemple:

arrays.txt

[0, 1, 10, 5, 40, 1, 70] [12, 54, 6, 11, 1, 0, 50]

just that... two or more arrays with the brackets and nothing else..

I want to read each array and load them into variables to plot a graph in python using matplotlib

import matplotlib.pyplot as plt

# import arrays from file as variables
a = [array1]
b = [array2]

plt.plot(a)
plt.plot(b)
plt.show()

The only thing I need is how to read the arrays from the txt and load them into variables to plot them later...

I've searched a lot but also find too many ways to do a lot of things in python which is good but also overwhelming

1

There are 1 best solutions below

6
Andrej Kesely On BEST ANSWER

The format of the text file is really unfortunate - better to fix the source of the problem and output the values in standard format (like Json, XML, etc.)

You can try to manually parse the file (with re/json modules for example):

import json
import re

import matplotlib.pyplot as plt

with open("your_file.txt", "r") as f_in:
    data = re.sub(r"]\s*\[", r"], [", f_in.read(), flags=re.S)

data = json.loads(f"[{data}]")

for i, arr in enumerate(data, 1):
    plt.plot(arr, label=f"Array {i}")

plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.title(f"Graph of {len(data)} Arrays")

plt.legend()
plt.show()

Creates this graph:

enter image description here