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?
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:
Please check the snippet
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With