How to load a text file and plot multiple columns in a single figure

Viewed 2324

I have a text file with 5 columns. The 1st one is the X-axis (1,2,3,4), and the rest of the columns are for the y-axis. I want to plot them in one graph.

1 0 0 0 0
2 7 14 2.53381 0.0691848
3 6 16 2.61242 0.0507856
4 6 17 2.65154 0.040285

I am trying this code for a single y value.

import matplotlib.pyplot as plt
import numpy as np

file_name = input("Enter the file name:")

x, y = np.loadtxt(file_name, delimiter=',', unpack=True)
plt.plot(x,y, label='Loaded from file!')

plt.xlabel('Action')
plt.ylabel('Rate')
plt.title('Plot of Rate')
plt.legend()
plt.show()

How can multiple y values be extracted, and plotted?

4 Answers

Use *y to store all columns data(after x column) in y variable. Use delimite=' ' if your data is space-separated.

So just do this correction while loading file and leave other code as it is): x, *y = np.loadtxt(file_name, delimiter=',', unpack=True)

which results: enter image description here

Please check the snippet lines

import matplotlib.pyplot as plt
import pandas as pd
import matplotlib.ticker as ticker

df = pd.read_csv('samp.txt', sep=" ", header=None)
df.columns = ["x", "y1", "y2", "y3","y4"]
print(df)

fig, ax = plt.subplots()

ax.plot(df['x'],df['y1'], label='Line1')
ax.plot(df['x'],df['y2'], label='Line2')
ax.plot(df['x'],df['y3'], label='Line3')
ax.plot(df['x'],df['y4'], label='Line4')
tick_spacing = 1
ax.xaxis.set_major_locator(ticker.MultipleLocator(tick_spacing))
plt.xlabel('Action')
plt.ylabel('Rate')
plt.title('Plot of Rate')
plt.legend()
plt.show()
  • The answer from Girish fixes the code in the OP, but this answer represents the least amount of code to produce the desired output.
  • Use pandas.read_csv to read in the file, and set column 0 as the index
    • Use sep='\\s+' based on the sample shown, but use the appropriate separator, if it's something other than what is in the OP.
    • Based on the sample, use header=None, but change it as needed for the file.
  • Use pandas.DataFrame.plot to plot the dataframe in 1 line.
  • Additionally, the benefit of using pandas is the data can now be easily analyzed. Try df.describe() to get column-wise statistics.
import pandas as pd

# read the file
df = pd.read_csv('file.txt', sep='\\s+', header=None, index_col=0)

# add column names if desired; the list must have as many values as there are columns
df.columns = ['a', 'b', 'c', 'd']

# plot the data
df.plot(figsize=(7, 4), xlabel='Action', ylabel='Rate', title='Plot of Rate')

enter image description here

  • Summary Statistics of Data
df.describe()

             a       b        c        d
count  4.00000   4.000  4.00000  4.00000
mean   4.75000  11.750  1.94944  0.04006
std    3.20156   7.932  1.30055  0.02926
min    0.00000   0.000  0.00000  0.00000
25%    4.50000  10.500  1.90036  0.03021
50%    6.00000  15.000  2.57312  0.04554
75%    6.25000  16.250  2.62220  0.05539
max    7.00000  17.000  2.65154  0.06918

So first I loaded the data into 4 variables, one of them is x and three of them are y1, y2, y3 and then I just used the method 'plot' three times in order to create thre different graphs

import matplotlib.pyplot as plt
import numpy as np

file_name = input("Enter the file name:")
data = np.loadtxt(file_name, delimiter=',', unpack=True)

x = data[0]
y1 = data[1] # the first graph
y2 = data[2] # the second graph
y3 = data[3] # the third graph
y4 = data[4] # the fourth graph

plt.plot(x,y1, label='y1')
plt.plot(x,y2, label='y2')
plt.plot(x,y3, label='y3')
plt.plot(x,y4, label='y3')
plt.xlabel('Action')
plt.ylabel('Rate')
plt.title('Plot of Rate')
plt.legend()
plt.show()

enter image description here

Related