Plot a poisson distribution graph in python - python

I would like to plot the Poisson function in Python using Matplotlib. The function is (exp(-5)*5^x)/factorial(x)
import numpy as np
import math
import matplotlib.pyplot as plt
t = np.arange(0, 20, 0.1)
d = []
for i in t:
p = pow(5,i)
q = p/math.factorial(i)
d.append(q)
plt.plot( t, np.exp(-5)*d, 'bs')
plt.show()
But I get this error."Only size^1 arrays can be converted to Python scalars". How can I plot this graph? Thanks in advance

i think your function is not right: it's exp(-5)
import numpy as np
import matplotlib.pyplot as plt
from scipy.special import factorial
t = np.arange(0, 20, 0.1)
d = np.exp(-5)*np.power(5, t)/factorial(t)
plt.plot(t, d, 'bs')
plt.show()

The immediate problem is probably that you are using 't' instead of 'i' in your loop. However, you may want to avoid mixing python lists with numpy arrays. You could do it like,
import numpy as np
import scipy.misc
import math
import matplotlib.pyplot as plt
t = np.arange(0, 20, 0.1)
x = np.power(t, 5)
y = scipy.misc.factorial(t)
plt.plot( t, x / y, 'bs')
plt.show()

Related

Fit of intensity distribution does not work

So im sitting here and don't know how to fit the right function for my Intensity distribution of a doubleslit experiment. I tried so much but I don't know how it works. The x,y data are more than 1000 values.
Here is my Plot:
And here's how it should look like:
And that is my code to that:
import matplotlib.patches as mp
import matplotlib.pyplot as plt
import numpy as np
from scipy import optimize
from scipy.optimize import curve_fit
import pandas as pd
import math
data = pd.read_csv('TEM00-Doppelspalt-Short.txt',sep='\s+',header=None)
data = pd.DataFrame(data)
x = data[1]
y = data[2]
def expf(i0,g,k,y0,d):
return i0*((np.sin(g*(k-y0)))/(g*(k-y0)))**2*np.cos(d*(k-y0))**2
popt, pcov =curve_fit(expf, x, y, p0 = (13, 20, 2, 4))
g,k,y0,d = popt
plt.figure(figsize = (8,6), dpi = 600)
plt.xlabel(r'Wavelength [$\mu$m]',fontsize=12)
plt.ylabel('Value [Cnts]', fontsize=12)
plt.plot(x, y,'ko')
plt.plot(x, expf(x,g,k,y0,d))
a_patch=mp.Patch(color='k', label="$TEM_{00}$ Doubleslit ShortMode")
plt.legend(handles=[a_patch],loc="upper left")
plt.show()
Here is my datafile:
Data File of Intensity

How to solve Axes3D error when plotting a function?

I have a code to graph mi function f(x,y)=(x^4 + y^4). I already imported all the necessary libraries, but when i run it, the "MatplotlibDeprecationWarning: Axes3D(fig) adding itself to the figure is deprecated since 3.4. Pass the keyword argument auto_add_to_figure=False and use fig.add_axes(ax) to suppress this warning. The default value of auto_add_to_figure will change to False in mpl3.5 and True values will no longer work in 3.6. This is consistent with other Axes classes." error shows.
This is my code:
`
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
figura = plt.figure()
ejes = Axes3D(figura)
plt.show()
def f(x,y):
return ((x**4)+(y**4))
x = np.linspace(-2,2,40)
y = np.linspace(-2,2,40)
x,y = np.meshgrid(x,y)
z= f(x,y)
ejes.plot_wireframe(x,y,z)
`
On my environment it actually works. Anyway you can obtain the same plot using the "3d" projection of pyplot:
import numpy as np
import matplotlib.pyplot as plt
figura = plt.figure(figsize=(7,7))
ejes = plt.subplot(111, projection="3d")
def f(x,y):
return ((x**4)+(y**4))
x = np.linspace(-2,2,40)
y = np.linspace(-2,2,40)
x,y = np.meshgrid(x,y)
z= f(x,y)
ejes.plot_wireframe(x,y,z)
plt.show()

How can I plot with a fewer markers than the data points?

My data on x goes from 3MHz to 12MHz, I don't want show all those points on the x-axis instead I want to show an interval of from 3MHz to 12MHz spaced out one 1MHz a part.
Here is an example code.
import numpy as np
import matplotlib.pyplot as plt
x_array = np.arange(3000000, 12000000)
y_array = np.arange(3000000, 12000000)
plt.plot(x_array, y_array)
plt.show()
I want the x-axis first marker to to be 3MHz second marker to be 4MHz and so on up to 12MHz.
You want to have MHz on the x-axis? then use mega Hertz in the definition of the x array and multiply by 10⁶ when you use the array as a frequency in a subsequent calculation
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(3, 12, 901)
f = x*1E6
def H(f) : return f
plt.plot(x, H(f))
plt.xticks(range(3, 13))
plt.xlabel('Frequency/MHz')
plt.ylabel('Transfer function')
plt.grid()
plt.show()
You can change the matplotlib xticks using the following:
plt.xticks(np.arange(3000000, 12000000, step=1000000))
Defining the step will ensure you have 1MHz space.
You can find more here:
https://numpy.org/doc/stable/reference/generated/numpy.arange.html
https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.xticks.html
Edit:
If you want to have the MHz on the x ticks, you can do the following:
import numpy as np
import matplotlib.pyplot as plt
x_array = np.arange(3000000, 12000000)
y_array = np.arange(3000000, 12000000)
plt.plot(x_array, y_array)
plt.xticks(ticks=np.arange(3, 13)*1e6, labels=[str(t) + "MHz" for t in np.arange(3, 13)])
plt.show()
Output: https://i.stack.imgur.com/JdIM3.png
Otherwise, you can do as mentioned in the other answer:
import numpy as np
import matplotlib.pyplot as plt
x_array = np.arange(3000000, 12000000)
y_array = np.arange(3000000, 12000000)
plt.plot(x_array, y_array)
plt.xticks(ticks=np.arange(3, 13)*1e6, labels=np.arange(3, 13))
plt.xlabel("Frequency (MHz)")
plt.show()
Output: https://i.stack.imgur.com/Vc1gb.png2

Plot Square Wave in Python

Im currently working on graphing a square wave in python using numpy and pylot.
How would I plot a square wave function over multiple periods of T?
I currently have:
from scipy import signal
import numpy as np
from scipy.fftpack import fft
#Initialize Parameters
p_0 = 2
A = np.sqrt(1/(2*p_0))
t = [-A,A]
plt.plot(t,[A,A])
plt.show()
which just gives me a straight line.
The end game is to take the Fourier transform of the square wave function
You could use the square function from scipy.signal
from scipy import signal
import matplotlib.pyplot as plt
t = np.linspace(0, 1, 500, endpoint=False)
plt.plot(t, signal.square(2 * np.pi * 5 * t),'b')
plt.ylim(-2, 2)
plt.grid()
plt.show()
This code below will do the trick:
import math, numpy
from matplotlib import pyplot as plt
x = numpy.linspace(0, 10, 1000)
y = numpy.array([1 if math.floor(2 * t) % 2 == 0 else 0 for t in x])
plt.plot(x,y)
plt.show()
If the math.floor(2 * t) % 2 == 0 returns True plot 1 else plot 0.
Output:

Color area beneath sympy function plot

I have a sympy function, I want to plot it and color the area beneath the curve, how can I do it?
Code
import sympy as sy
x = sy.symbols('x')
f = sy.sin(x)
sy.plot(f, (x, 0, sy.pi))
Plot
i have created the same output without using matplotlib directly(sympy already uses sympy)
import sympy as sy
import numpy as np
from sympy.plotting import plot
x = sy.symbols('x')
f = sy.sin(x)
x_array = np.linspace(0, np.pi, 1000)
f_array = sy.lambdify(x, f)(x_array)
plot(f, (x, 0, sy.pi), fill={'x': x_array,'y1':f_array,'color':'green'})
i got the output
You can use plt.fill_between (documentation) but you need to convert your sympy function in a numpy array with sy.lambdify (documentation) before, because plt.fill_between takes in arrays.
Check this code as a reference:
import sympy as sy
import numpy as np
import matplotlib.pyplot as plt
x = sy.symbols('x')
f = sy.sin(x)
x_array = np.linspace(0, np.pi, 1000)
f_array = sy.lambdify(x, f)(x_array)
fig, ax = plt.subplots()
ax.plot(x_array, f_array, color = 'red')
ax.fill_between(x_array, f_array, facecolor = 'red', alpha = 0.3)
plt.show()

Categories