Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 781
jonson Avatar asked Sep 19 '25 02:09

jonson


2 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

like image 54
Girish Hegde Avatar answered Sep 21 '25 17:09

Girish Hegde


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()
like image 36
Karthik Avatar answered Sep 21 '25 16:09

Karthik