Home > Software design >  Creating a line graph of numbers from a .txt file
Creating a line graph of numbers from a .txt file

Time:04-05

I have a text file containing a series of numerical values. Lets say the .txt file is called numbers.txt and it contains the values (283, 927, 273, 284, 251). How do I use python to create a line graph of these values?

The x-axis tells us what position the number is in within the series. For instance, 927 is 2nd so x=2. In other words the coordinates would be (1, 283), (2, 927) etc.

Thank you

CodePudding user response:

The file numbers.txt contains:

283, 927, 273, 284, 251

With numpy and matplotlib:

import numpy as np
import matplotlib.pyplot as plt
data = np.loadtxt("/path/to/your/numbers.txt", delimiter=",")
plt.figure()
plt.plot(range(len(data)), data)
plt.show()

CodePudding user response:

You may need to install matplotlib with python -m pip install matplotlib.

import matplotlib.pyplot as plt

# Get data from our file
with open('my_file_name.txt', 'r') as f:
   text = f.read() 

# This part really depends on how your txt data is formatted
text = text.replace(")", "")
text = text.replace("(", "")
text = text.replace(" ", "")
text_list = text.split(",")

# Turn our list of strings into a list of numbers
y_values = [float(i) for i in text_list]

# Get a list of x-values to correspond with our y-values
count = len(number_list)
x_values = [i for i in range(1, count   1)]

# Plot it
plt.plot(x_values, y_values)
plt.show()

Let me know if you have any specific questions. I know a lot of the syntax may be foreign if you're new to Python. I also didn't test the script, so comment if it fails.

CodePudding user response:

Say you have called numbers.txt with the following contents:

283, 927, 273, 284, 251

You could use Graph

  • Related