Plot multiple graphs without using a for loop - numpy

So, my question may not be exactly what is in the title.
I have a function
y = a*x + b
And I want to plot y whith different values of b.
I know that I can do the following:
import numpy as np
import matplotlib.pyplot as plt
a = 2
x = np.array([0,1,2,3,4])
b = 0
for i in range(10):
y = a*x + b
b = b+1
plt.plot(x,y)
And that returns exactly what I want.
But, there is someway that I can make this by using
b = np.array([0,1,2,3,4,5,6,7,8,9])? So, then my code could look something like:
import numpy as np
import matplotlib.pyplot as plt
a = 2
x = np.array([0,1,2,3,4])
b = np.array([0,1,2,3,4,5,6,7,8,9])
y = a*x + b
plt.plot(x,y)

Yes, you can use matrix operations to create a 2D matrix with the result of the operation y = a*x + b.
a = 2
x = np.array([0,1,2,3,4])
b = np.array([0,1,2,3,4,5,6,7,8,9])
y = a*x[:,None]+b
plt.plot(x, y)
EDIT: I'm shwing the solution provided by #Quang Hoang which is much simpler than mine.
original code was:
y = np.tile(a*x, (b.size,1)) + b[:,np.newaxis]
plt.plot(x, y.T)

Related

centre the peak at x=0

Right now the rectangle signal is centre on x = 4, how can I make it centre on x = 0
def rect(n,T):
a = np.zeros(int((n-T)/2,))
b = np.ones((T,))
c= np.zeros(int((n-T)/2,))
a1 = np.append(a,b)
a2 = np.append(a1,c)
return a2
x =rect(11,6)
plt.step(x, 'r')
plt.show()
This is so far that I wrote. Appreciate anyone can give the Idea
A method to center the rectangle at x=0 is to provide x values to plt.step. One way to accomplish this is to use numpy arange and center the x values around 0 by using the length of a2 returned in the rects function
# Changed to y because it will be our y values in plt.step
y = rect(11, 6)
# Add 0.5 so it's centered
x = np.arange(-len(y)/2 + 0.5, len(y)/2 + 0.5)
And then plot it using plt.step and setting where to mid (more info in the plt.step docs):
plt.step(x, y, where='mid', color='r')
Hope this helps. Here is the full code:
import numpy as np
import matplotlib.pyplot as plt
def rect(n, T):
a = np.zeros(int((n-T)/2,))
b = np.ones((T,))
c = np.zeros(int((n-T)/2,))
a1 = np.append(a, b)
a2 = np.append(a1, c)
return a2
y = rect(11, 6)
# Add 0.5 so it's centered
x = np.arange(-len(y)/2 + 0.5, len(y)/2 + 0.5)
plt.step(x, y, where='mid', color='r')
plt.show()

list index out of range _ UNET

I would be grateful if you can help me solve the problem
import matplotlib.pyplot as plt
import tifffile as tiff
import os
rows = 3
cols = 4
axes=[]
fig=plt.figure(figsize=[10,10])
i=["/images/1","/masks/1","/images/2","/masks/2"]
i=i+["/images/3","/masks/3","/images/4","/masks/4"]
p=1
m=0
for a in range(rows*cols):
if i[m].find("masks")!=-1:
b = plt.imread("/content/drive/MyDrive/PFE_MOHTICH/dataset/data/test{}.png".format(str(i[m])))
else:
b = tiff.imread("/content/drive/MyDrive/PFE_MOHTICH/dataset/data/test{}.tiff".format(str(i[m])))
m=m+1
axes.append( fig.add_subplot(rows, cols, a+1) )
plt.imshow(b)
plt.savefig("ex_val.png",cmap='binary_r')
fig.tight_layout()
plt.show()
The line which results in an error
(if i[m].find("masks")!=-1) :
the error message:
list index out of range
I don't know what's hard to see in this. Your for loop
for a in range(rows*cols): #rows*cols = (3*4) = 12
# In this loop you update m every iteration
m = m+1
so your m goes from 0 to 11 while your i has only 8 elements.
Like what is it that you can't see/get?

How to develop a function

I am completely new in python and I am learning it. I have written the following code but i couldnt make any functions of it. Can somebody help me please?
import pandas as pd
import numpy as np
f = open('1.csv', 'r')
df = pd.read_csv(f, usecols=[0], sep="\t", index_col=False)
Primary_List = df.values.tolist()
x = 0
y = len(Primary_List)
for i in range(x, y):
x = i
MyMatrix = Primary_List[x:x + 10]
print(MyMatrix)
You could create a function where you pass in the filename, then you could use this code to read and print many csv files.
def createMatrix(filename):
f = open(filename, 'r')
df = pd.read_csv(f, usecols=[0], sep="\t", index_col=False)
Primary_List = df.values.tolist()
x = 0
y = len(Primary_List)
for i in range(x, y):
x = i
MyMatrix = Primary_List[x:x + 10]
return MyMatrix
print(createMatrix('1.csv'))
print(createMatrix('2.csv'))
print(createMatrix('3.csv'))

tensorflow ValueError: Shape must be rank 1 but is rank 2

import tensorflow as tf
x = [[1,2,3],[4,5,6]]
y = [0,1]
z = [1,2]
x = tf.constant(x)
y = tf.constant(y)
z = tf.constant(z)
m = x[y,z]
What I expect is m = [2,6]
I can get the result by theano or numpy. How I get the result using tensorflow?
You would want to use tf.gather_nd
slices = tf.gather_nd(x, [y, z])
Hope this helps.

Printing the equation of the best fit line

I have created the best fit lines for the dataset using the following code:
fig, ax = plt.subplots()
for dd,KK in DATASET.groupby('Z'):
fit = polyfit(x,y,3)
fit_fn = poly1d(fit)
ax.plot(KK['x'],KK['y'],'o',KK['x'], fit_fn(KK['x']),'k',linewidth=4)
ax.set_xlabel('x')
ax.set_ylabel('y')
The graph displays the best fit line for each group of Z. I want print the equation of the best fit line on top of the line.Please suggest what can i do out here
So you need to write some function that convert a poly parameters array to a latex string, here is an example:
import pylab as pl
import numpy as np
x = np.random.randn(100)
y = 1 + 2 * x + 3 * x * x + np.random.randn(100) * 2
poly = pl.polyfit(x, y, 2)
def poly2latex(poly, variable="x", width=2):
t = ["{0:0.{width}f}"]
t.append(t[-1] + " {variable}")
t.append(t[-1] + "^{1}")
def f():
for i, v in enumerate(reversed(poly)):
idx = i if i < 2 else 2
yield t[idx].format(v, i, variable=variable, width=width)
return "${}$".format("+".join(f()))
pl.plot(x, y, "o", alpha=0.4)
x2 = np.linspace(-2, 2, 100)
y2 = np.polyval(poly, x2)
pl.plot(x2, y2, lw=2, color="r")
pl.text(x2[5], y2[5], poly2latex(poly), fontsize=16)
Here is the output:
Here's a one liner.
If fit is the poly1d object, while plotting the fitted line, just use label argument as bellow,
label='y=${}$'.format(''.join(['{}x^{}'.format(('{:.2f}'.format(j) if j<0 else '+{:.2f}'.format(j)),(len(fit.coef)-i-1)) for i,j in enumerate(fit.coef)]))