<jupyter_start><jupyter_text>This script explains- to create numpy arrays, transpose and their additions - to save multidimensional array in a txt file- read the txt file- read the mixdata type txt file- read csv file- plot the data - multi plot the data \Format is like this: numpy.loadtxt(fname, dtype=, comments='', delimiter=None, converters=None, skiprows=0, usecols=None, unpack=False, ndmin=0, encoding='bytes', max_rows=None, *, like=None) \np.savetxt(f, arexp) \<jupyter_code>import matplotlib.pyplot as plt
import numpy as np<jupyter_output><empty_output><jupyter_text>create multidimensional arrary<jupyter_code>t = np.arange(1, 5.0, 0.1)               #create one dimensional array, (start, end, interval)
#print(t)
#print(type(t))
data1 = np.exp(t)                         #array of exponential function
data2 = np.sin(2 * np.pi * t)             #array of exponential function
data3 = np.cos(2 * np.pi * t)

sqdata1 = np.exp(t)**2                   #square of above functions
sqdata2 =np.sin(2 * np.pi * t)**2
sqdata3 = np.cos(2 * np.pi * t)**2

#print(t.dtype)
#print(t)
type(data1)

# convert/transform row into column
#
tt = t.reshape(-1,1)                  #convert one dimensional array into column
#print(t)
#print(tt)

tdata1 = data1.reshape(-1,1)
#print(data1)
#print(tdata1)

tdata2 = data2.reshape(-1,1)
#print(data2)
#print(tdata2)

tdata3 = data3.reshape(-1,1)
#print(data3)
#print(tdata3)

tsqdata1 = sqdata1.reshape(-1,1)
#print(tsqdata1)
tsqdata2 = sqdata2.reshape(-1,1)
tsqdata3 = sqdata3.reshape(-1,1)

arexp = np.concatenate((tt,tdata1,tsqdata1),axis = 1)
arsin = np.concatenate((tt,tdata2,tsqdata2),axis = 1)
arcos = np.concatenate((tt,tdata3,tsqdata3),axis = 1)
#print(arexp)
# OR using column_stack
#arexp = np.column_stack([tt,tdata1,tsqdata1])
#arsin = np.column_stack([tt,tdata2,tsqdata2])
#arcos = np.concatenate([tt,tdata3,tsqdata3])<jupyter_output><empty_output><jupyter_text>- understand the reshape command \https://numpy.org/doc/stable/reference/generated/numpy.reshape.html<jupyter_code>a = np.arange(6)
#print(a)
#print(type(a))
#print(np.shape(a))

#a = np.arange(6).reshape((3, 2))
aa = a.reshape((3, 2))
#print(aa)
#print(np.shape(aa))

b = np.arange(6).reshape((2, 3))
#print(b)

c = np.arange(6).reshape((1, 6))
#print(c)
d = c.reshape(6,1)          #if we know the length/shape of array
#print(d)
rs = len(d)
dd = c.reshape(rs,1) 
#print(dd)

#make one column
print(np.shape(d))
no_rows = np.shape(d)[0]
print(no_rows)
no_columns = np.shape(d)[1]
cc = c.reshape(no_rows,1)
#print(cc)

#make one column
e = c.reshape(-1,1)         #if length/shape of array is not defined
#print(e)<jupyter_output>(6, 1)
6<jupyter_text>save array in a txt file or csv file<jupyter_code>'''
with open("test4multiplot.txt", "a") as f:
    f.write("#exponential from here\n")
    np.savetxt(f, arexp)
    f.write("#sine from here\n")
    np.savetxt(f, arsin)
    f.write("#cosine from here\n")
    np.savetxt(f, arcos)
'''
#header automatically take # at start, delimiter=',' for making csv file
#
with open("newsomething.csv", "w") as f:
    np.savetxt(f, arexp, fmt='%12.4f', header = "exponential function; t, exp(t), (exp(t))**2", delimiter=',')
    #np.savetxt(f, arexp, fmt='%12.2f', header = "exponential function; t, exp(t), (exp(t))**2", delimiter=',')
    np.savetxt(f, arsin, fmt='%12.2f', header = "sin function; t, sin(2*pi*t), (sin(2*pi*t)**2)", delimiter=',')
    np.savetxt(f, arcos, fmt='%12.2f', header = "cos function; t, cos(2*pi*t), (cos(2*pi*t)**2)", delimiter=',')<jupyter_output><empty_output><jupyter_text>practice to understand loadtxt.<jupyter_code>#data = np.loadtxt("testData.txt")                    #if data are integer or float only
#data = np.loadtxt("testData.txt", dtype = str)       # if data contains strings or / or : too
#data = np.loadtxt("testData.txt", dtype = str)       # by default loadtxt reads the folat data
#data = np.loadtxt("testData.txt", dtype = str, delimiter = ",")         # this seems we can read csv file too
#data = np.loadtxt("testData.txt", delimiter = ",")                      # this seems we can read csv file too
#data = np.loadtxt("testcsv.csv", delimiter = ",")                       # this seems we can read csv file too
#data = np.loadtxt("testcsv.csv", dtype = str, delimiter = ",")           # this seems we can read csv file too

#print("shape of data:",data.shape)
#print("datatype of data:",data.dtype)

#print(data[0,:])
'''
contents of testData.txt
#----------------
#this is test file

#ram 10 200.0
#shyam 20  400.5
#gita  16 600.5
#
#10 20
#2.0 50.5
#
#1 2
#3 4
1,2
3,4
#--------------
and contents of testcsv.csv

#2,3
#5,8
#10.,20
a,fine,30
b,good,20
c,excellent,15

'''<jupyter_output><empty_output><jupyter_text>read the saved txt file<jupyter_code>ar = np.loadtxt("newsomething.csv",delimiter = ',')
#ar = np.loadtxt("test4multiplot.txt", delimiter = ',')   # if file is csv type
#data = np.loadtxt("test4multiplot.txt", dtype = str)     #if file contains multiple data types
#print(data)
#data.shape
ar.shape
#print(ar)
# if the file contains multile data like string and float then convert suitable shape of data into float
#ar = np.array(data[:,2:])  #so far data in the form of string
#ar = data[:,:].astype(np.float)  # converted into float except 1st and 2nd column
# details: https://numpy.org/doc/stable/reference/generated/numpy.ndarray.astype.html
# astype: Copy of the array, cast to a specified type.
#print(ar[0:2,:])
#type(ar)
#print(ar.shape)
r_te = ar[0:40,0]
#print(r_te)

r_exp = ar[0:40,1]
r_sqexp = ar[0:40,2]
#print(r_exp)
#print(r_sqexp)

r_ts = ar[41:80,0]
r_sin = ar[41:80,1]
r_sqsin = ar[41:80,2]
#print(r_sin)
#print(r_sqsin)

r_tc = ar[81:120,0]
r_cos = ar[81:120,1]
r_sqcos = ar[81:120,2]
#print(r_cos)
#print(r_sqcos)<jupyter_output><empty_output><jupyter_text>plot the data with multiple vertical axes plot 1: simple plot<jupyter_code>f_size = 20   #font size
l_width = 3  #line width

fig, plot1 = plt.subplots(figsize=(7,5)) #this is host plot
plt.xticks(fontsize=f_size)
plt.yticks(fontsize=f_size)
#plot1.set_title('Title: Overlay plots',fontsize=f_size)

p1 = plot1.plot(r_te, r_exp, color="red", linewidth = l_width, label = 'Exponential')
p2 = plot1.plot(r_ts, r_sin, color="blue", linewidth = l_width, label = 'Sine')
p3 = plot1.plot(r_tc, r_cos, color="black", linewidth = l_width, linestyle='--',marker='o', label = 'cosine')

plot1.set_xlabel('Time (s)', fontsize = f_size)
plot1.set_ylabel('Functions',  fontsize = f_size)
plot1.tick_params(axis='both', direction='out')   #direction = 'in', 'out', 'inout'
#plot1.set_xlim(0,5)
#plot1.set_ylim(-2, 14)
plt.axis([0,5, -2, 6])                         #axis[xmin,xmax, ymin,ymax]
#another way to set axis limit
#plt.xlim(xmin,xmax)
#plt.ylim(ymin,ymax)
plt.text(2, 2.5, "...we need 2nd y-scale !!", fontsize = f_size, color = "orange")

legnds = p1+p2+p3
labs = [l.get_label() for l in legnds]
plot1.legend(legnds, labs,  fontsize = f_size-2, loc=0)  #loc is use for location, eg., 0 , "upper left"

#plot1.grid(True)

fig.tight_layout()  # otherwise the right y-label is slightly clipped
plt.savefig("multiyaxisplot0.png")
plt.show()<jupyter_output><empty_output><jupyter_text>plot 2: plot with 2 vertical axes<jupyter_code>f_size = 18   #font size
l_width = 2   # line width

fig, plot1 = plt.subplots(figsize=(7,5)) #this is host plot
plt.xticks(fontsize=f_size)
plt.yticks(fontsize=f_size)

color1 = 'red'   # color1 = 'tab:red'
plot1.set_xlabel('Time (s)', fontsize = f_size)
plot1.set_ylabel('Exponential', color=color1, fontsize = f_size)
p1 = plot1.plot(r_te, r_exp, color=color1, linewidth = l_width, label = 'Exponential')
plot1.tick_params(axis='y', direction='in', labelcolor=color1)
#plot1.tick_params(axis='both', direction='in', labelcolor=color1)
plot1.tick_params(axis='x', direction='in')
#plot1.tick_params(axis='y', direction='in', labelcolor=color1)

plot2 = plot1.twinx()  # plot1 and plot2 share the same x-axis

color2 = 'tab:blue'  
plot2.set_ylabel('Sin and Cos', color=color2, fontsize = f_size)  
p2 = plot2.plot(r_ts, r_sin, color=color2, linewidth = l_width, label = 'Sine')
plot2.tick_params(axis='y', direction='in', labelcolor=color2, labelsize=f_size)

plot3 = plot1.twinx()  # plot1 and plot2 share the same x-axis
#plot3.spines["right"].set_position(("axes", 1.2))  #if you use another versitcal axis
#plot3.axis["right"].label.set_fontsize(18)

color3 = 'tab:orange'
plot3.set_ylabel('Cos', color=color3, fontsize = f_size)  
p3 = plot3.plot(r_tc, r_cos, color=color3, linewidth = l_width, linestyle='--',marker='o', label = 'cosine')
plot3.tick_params(axis='y', direction='in', labelcolor=color3, labelsize=f_size) #where you want to plot it in plot3 or plot2 or plot1, use that
plot3.axes.get_yaxis().set_visible(False)  #comment it for separte vertical axis
#plot3.yticks(fontsize=f_size)

plot1.set_xlim(0,5)
plot1.set_ylim(0, 100)
plot2.set_ylim(-2, 2)
plot3.set_ylim(-2, 2)

legnds = p1+p2+p3
labs = [l.get_label() for l in legnds]
plot1.legend(legnds, labs,  fontsize = f_size-5, loc=0)  #loc is use for location, eg., 0 , "upper left"

#plot1.grid(True)

fig.tight_layout()  # otherwise the right y-label is slightly clipped
plt.savefig("multiyaxisplot1.png")
plt.show()<jupyter_output><empty_output><jupyter_text>plot 3: plot with 3 vertical axes<jupyter_code>f_size = 15  # font size
l_width = 3  #line width

fig, plot1 = plt.subplots(figsize=(7,5)) #this is host plot
plt.xticks(fontsize=f_size)
plt.yticks(fontsize=f_size)

color1 = 'red'  #color1 = 'tab:red'
plot1.set_xlabel('Time (s)', fontsize = f_size)
plot1.set_ylabel('Exponential', color=color1, fontsize = f_size)
p1 = plot1.plot(r_te, r_exp, color=color1, linewidth = l_width, label = 'Exponential')
plot1.tick_params(axis='y', labelcolor=color1)

plot2 = plot1.twinx()  # plot1 and plot2 share the same x-axis

color2 = 'blue'
plot2.set_ylabel('Sin', color=color2, fontsize = f_size)  
p2 = plot2.plot(r_ts, r_sin, color=color2, linewidth = l_width, label = 'Sine')
plot2.tick_params(axis='y', labelcolor=color2, labelsize=f_size)
#plt.legend(loc = "lower left")

plot3 = plot1.twinx()  # plot1 and plot2 share the same x-axis
plot3.spines["right"].set_position(("axes", 1.2))  #if you use another versitcal axis
#plot3.axis["right"].label.set_fontsize(18)

color3 = 'green'
plot3.set_ylabel('Cos', color=color3, fontsize = f_size)  
p3 = plot3.plot(r_tc, r_cos, color=color3, linewidth = l_width, linestyle='--',marker='o', label = 'cosine')
plot3.tick_params(axis='y', labelcolor=color3, labelsize=f_size) #where you want to plot it in plot3 or plot2 or plot1, use that
#plot3.axes.get_yaxis().set_visible(False)  #comment it for separte vertical axis
#plot3.yticks(fontsize=f_size)
#plt.legend()

plot1.set_xlim(0,5)
plot1.set_ylim(0, 100)
plot2.set_ylim(-2, 6)
plot3.set_ylim(-4, 4)

lns = p1+p2+p3
labs = [l.get_label() for l in lns]
plot1.legend(lns, labs,  fontsize = f_size-2, loc=0)

#plot1.grid(True)

fig.tight_layout()  # otherwise the right y-label is slightly clipped
plt.savefig("multiyaxisplot2.png")
plt.show()<jupyter_output><empty_output><jupyter_text>plot 4: multiple plots (tiled figures)<jupyter_code>plt.figure(figsize = [15,10])

plt.subplot(2,2,1)
plt.plot(r_te, r_exp, linewidth=2, linestyle='-',marker='', color = 'black', label="Exp")
#plt.title('Field due to DQ7 at DQ7', fontsize=16)
#plt.xlabel('DQ7 current [A]', fontsize=14)
plt.ylabel('Functions', fontsize=14)
#plt.tight_layout()                             # this is for margin
plt.grid(True)                                 # comment this if u do not need grid
plt.legend()

plt.subplot(2,2,2)
plt.plot(r_ts, r_sin, linewidth=2, linestyle='-',marker='', color = 'black', label="Sin")
#plt.ylabel('By  at DQ7 [G]', fontsize=14)
#plt.xlabel('Time [unit]', fontsize=14)
plt.grid(True)                                 # comment this if u do not need grid
plt.legend()

plt.subplot(2,2,3)
plt.plot(r_tc, r_cos, linewidth=2, linestyle='-',marker='', color = 'black', label="Cos")
plt.ylabel('Function', fontsize=14)
plt.xlabel('Time [unit]', fontsize=14)
plt.grid(True)                                 # comment this if u do not need grid
plt.legend()

plt.subplot(2,2,4)
plt.plot(r_tc, r_sqcos, linewidth=2, linestyle='-',marker='', color = 'black', label="cos^2")
#plt.ylabel('Bz  at DQ7 [G]', fontsize=14)
plt.xlabel('Time [unit]', fontsize=14)
plt.grid(True)                                 # comment this if u do not need grid
plt.legend()

plt.savefig("multiyaxisplot3.png")                    # png, jpg, eps, pdf as u like
plt.show()<jupyter_output><empty_output><jupyter_text>plot 5: plot with error bars<jupyter_code>f_size = 18   #font size
fig, plot1 = plt.subplots(figsize=(7,5)) #this is host plot
plt.xticks(fontsize=f_size)
plt.yticks(fontsize=f_size)

errbarexp = 0.1*r_exp
errbarcos = 0.5*r_cos

p1 = plot1.errorbar(r_te, r_exp, yerr = errbarexp, color="red", linewidth = 4, label = 'Exponential')
p2 = plot1.plot(r_ts, r_sin, color="blue", label = 'Sine')
p3 = plot1.errorbar(r_tc, r_cos, yerr = errbarcos, color="blue", linestyle='--',marker='o', label = 'cosine')

plot1.set_xlabel('Time (s)', fontsize = f_size)
plot1.set_ylabel('Functions',  fontsize = f_size)
plot1.tick_params(axis='both', direction='in')
#plot1.set_xlim(0,5)
#plot1.set_ylim(-2, 14)
plt.axis([0,5, -2, 10])                         #axis[xmin,xmax, ymin,ymax]
#another way to set axis limit
#plt.xlim(xmin,xmax)
#plt.ylim(ymin,ymax)

#legnds = p1+p2+p3
#labs = [l.get_label() for l in legnds]
#plot1.legend(legnds, labs,  fontsize = f_size-2, loc=0)  #loc is use for location, eg., 0 , "upper left"
plt.legend(fontsize = f_size-2)
#plot1.grid(True)

fig.tight_layout()  # otherwise the right y-label is slightly clipped
plt.savefig("multiyaxisplotErr.png")
plt.show()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1664248403946605, 'fraction_numerical': 0.03620139291932675, 'mean_word_length': 4.689228229467602, 'pattern_counts': {'":': 0, '<': 44, '<?xml version=': 0, '>': 44, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 5, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '11', 'dir': 'jupyter-structured-clean-dedup', 'id': '243893', 'license': 'MIT', 'n_tokens_mistral': 5756, 'n_tokens_neox': 5499, 'n_words': 1248, 'path': 'numpy_input_output_multiplot.ipynb', 'repo_name': 'AmbaPant/learning_numpy_amba', 'size': '13784'}