1

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
  • use ast model to convert the string representation of arrays to actual lists using ast.literal_eval arrays = [ast.literal_eval(array_str) for array_str in content.split()] Commented Jan 6, 2024 at 21:09

1 Answer 1

0

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

Sign up to request clarification or add additional context in comments.

6 Comments

That works beautifuly! I agree with fixing how the system export to the txt file... what will be the better way? this is how its saving the arrays at the moment... ` fileName = 'test.txt' file = open(fileName, "w") print(array_1, array_2, file=file) file.close() `
@BrunoMendes Look at python's json module. json.dump for creating json file/json.load for parsing the json file.
still confused with python syntax... definitely will do that... thanks!
@BrunoMendes Or consider using numpy and saving numpy arrays using np.save/np.savez and loading them back in using np.load.
@jared I tried that but, to be honest, found it a bit overwhelming all the info about it... as what i was trying to do is really simple...
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.