The asymptotic series plot is empty - python

I'm trying to plot the graph for this asymptotic series a_k = -k!(-x)**(k+1), with x=8, for k = 0,1,2,3......20, but my graph has no points in it.
Here is my code.
import numpy as np
import matplotlib.pyplot as plt
from scipy.special import factorial
k = np.linspace(0.0, 30.0, 10)
a_k = -factorial(k)*(-8)**(k+1)
plt.semilogy(k,a_k,'b-')
plt.xlabel("k")
plt.ylabel("a_k")
plt.title("Asymptotic series with x = 8")
plt.show()

Related

Python, loop adds too many yticks in sublot

I am subplotting over a loop, but the output is really crappy. I think it's stacking each single yticks.
Image Output
I need to give the image a single y axis, that's why I'm saving y_max and y_min for each iteration.
import matplotlib.pyplot as plt
import scipy
from scipy.optimize import curve_fit
from matplotlib import rc
rc('text', usetex=True)
import numpy as np
import math
from ctypes import *
import sys
np.finfo(np.dtype("float64"))
correlation_elements = 5
y_mag_max = np.zeros(correlation_elements)
y_mag_min = np.zeros(correlation_elements)
for i in range (correlation_elements):
fig_correl = plt.figure("correlations")
fig_correl.suptitle('Correlations')
start = i
end = i+correlation_elements
energy_correl_array = np.linspace(start, end, correlation_elements)
ax_correl_1 = fig_correl.add_subplot(1, 1, 1)
correlation_x_axis = np.linspace(0, correlation_elements-1, correlation_elements)
ax_correl_1.plot(correlation_x_axis, energy_correl_array,'.', label=r'$beta$ = {val:}'.format(val=i))
y_mag_max[i] = np.max(energy_correl_array)
y_mag_min[i] = np.min(energy_correl_array)
#Plotting Correlations
fig_correl.legend()
y_max = np.max(y_mag_max)
y_min = np.min(y_mag_min)
ax_correl_1.set_ylim(y_min, y_max)
ax_correl_1.set_ylabel('Energy')
plt.show()

Python : How I can draw FFT graph with Pandas DataFrame which is made by time and values

I am trying to make FFT graph which is derived from Pandas DataFrame.
It is my source code I tried with.
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from scipy.fft import fftfreq
plt.style.use("seaborn")
data = pd.read_csv("/Users/kyungyunlee/Desktop/ IRP reference/Data/PIXEL_DATA/1_piece.csv")
N = len(t)
t = data["time"].loc[data["time"] > 5].loc[data["time"] < 10]
s = data["y_value"].loc[data["time"] > 5].loc[data["time"] < 10]
print(len(s))
fft = np.fft.fft(s)
fftfreq = np.fft.fftfreq(len(s))
plt.subplot(1, 2, 1)
plt.xlabel("Frquency Domain")
plt.ylabel("Amplitude")
plt.plot(fftfreq, fft)
plt.subplot(1, 2, 2)
plt.plot(t, s)
plt.show()
And the picture below is the result of the source code.
As you can see from the graph, the left graph is FFT and the right graph is the time and amplitude graph. In this situation, I can't understand why my FFT graph is like that. The graph is weird but I can't find what the problem is.
enter image description here
Please check this Pandas dataframe screenshot. very simple data consist with time(maybe ms) and values.
time,y_value
5.009026,614
5.035417,550
5.061302,554
5.08712,611
5.114184,613
5.140525,614
5.167711,573
5.19439,532
5.220309,596
5.247532,607
5.273929,608
5.300062,588
5.326553,529
5.352314,577
5.378559,602
5.404629,602
5.431329,597
5.459119,547
5.486477,556
5.512459,597
5.539668,594
5.567103,597
5.594013,564
5.621206,539
5.646212,586
5.671964,594
5.698939,594
5.726222,577
5.777665,574
5.804736,590
5.831811,590
5.858152,583
5.885826,543
5.912285,562
5.937549,587
5.991617,585
6.018168,555
6.044418,547
6.07098,581
6.097121,585
6.124821,585
6.151159,566
6.177994,536
6.205361,573
6.232069,582
6.25743,582
6.284097,573
6.31036,537
6.336849,564
6.363457,580
6.390022,580
6.417727,576
6.444151,549
6.471022,553
6.498445,576
6.551982,577
6.578571,557
6.60393,544
6.631363,571
6.657855,576
6.685089,576
6.711603,563
6.763428,565
6.789426,574
6.815717,574
6.841412,569
6.867886,543
6.867886,517
6.89452,558
6.921834,572
6.974582,570
7.00143,550
7.029219,550
7.055249,569
7.109767,570
7.137385,556
7.188917,565
7.215901,569
7.215901,543
7.243045,569
7.270299,561
7.32553,560
What I want to do is to draw FFT graph with this Data but I don't know why the code is not working.
I hope I can get some feedbacks. Thank you.
If you suppress the DC node and adjust the axes, the results seem pretty reasonable:
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from scipy.fft import fftfreq
plt.style.use("seaborn")
data = pd.read_csv("x.data")
print(data)
t = data["time"].loc[data["time"] > 5].loc[data["time"] < 10]
s = data["y_value"].loc[data["time"] > 5].loc[data["time"] < 10]
fft = np.fft.fft(s)
fft[0] = 0
fftfreq = np.fft.fftfreq(len(s))*len(s)/(t.max()-t.min())
plt.subplot(1, 2, 1)
plt.xlabel("Frquency Domain")
plt.ylabel("Amplitude")
plt.plot(fftfreq, fft)
plt.subplot(1, 2, 2)
plt.plot(t, s)
plt.show()
Output:
And if you plot the power spectrum (np.abs(fft)), you get:

Python plotting lines parallel to y axis from array

I have an array containing 5 different numbers:
array([2.40064633, 4.10132553, 8.59968518, 2.40290345, 1.39988773]
and I want to plot the lines on the x axis (parallel to the y axis) equal to each of these numbers i.e.
x = 2.4006463
x = 4.10132553 so on and so forth for all of the numbers in the array.
I tried using plot(x = array[...]) but to no solution.
Is there a clean way of doing this using numpy or mathlab?
This will work:
import matplotlib.pyplot as plt
b =([2.40064633, 4.10132553, 8.59968518, 2.40290345, 1.39988773])
for l in b:
plt.axvline(l)
plt.show()
or is it an numpy array then:
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(1,4)
for l in x:
plt.axvline(l)
plt.show()
here is my take. quite the similar as Rahul's only with the lines harshed.
import matplotlib.pyplot as plt
import numpy as np
xcoords = np.array([2.40064633, 4.10132553, 8.59968518, 2.40290345, 1.39988773])
for xc in xcoords:
plt.axvline(x=xc, color='k', linestyle='--')

Python: how to define customized distributions?

I want to create a customized distribution based on a Levy truncated law, which reads
p(r) = (r + r0)**(-beta)*exp(-r/k).
So I defined it in the following way:
import numpy as np
import scipy.stats as st
class LevyPDF(st.rv_continuous):
def _pdf(self,r):
r0 = 100
k = 1500
beta = 1.6
return (r + r0)**(-beta)*np.exp(-r/k)
Suppose that I want to find the distribution of distances between r = 0 and r = 50km. Then:
nmin = 0
nmax = 50
my_cv = LevyPDF(a=nmin, b=nmax, name='LevyPDF')
x = np.linspace(nmin, nmax, (nmax-nmin)*2)
I do not understand why:
sum(my_cv.cdf(x)) = 2.22
instead of 1.
Then how can I define an histogram of N = 2000000 random distances based on the distribution that I defined?
Using your minimal example (slightly adapted):
import scipy.stats as st
import numpy as np
import matplotlib.pyplot as plt
class LevyPDF(st.rv_continuous):
def _pdf(self,r):
r0 = 100
k = 1500
beta = 1.6
return (r + r0)**(-beta)*np.exp(-r/k)
nmin = 0
nmax = 50
my_cv = LevyPDF(a=nmin, b=nmax, name='LevyPDF')
To sample from your random variable, use rvs() method from rv_continuous class:
N = 50000
X = my_cv.rvs(size=N, random_state=1)
Will return an array of size (N,) with random variates sampled from your distribution. Use random_state option to freeze your example and make your script repeatable (it defines random seed for your sampling).
Note as N softly increases, computation time drastically increases.
To plot histogram, use matplotlib library, see hist:
fig, axe = plt.subplots()
n, bins, patches = axe.hist(X, 50, normed=1, facecolor='green', alpha=0.75)
plt.show(axe)
Bellow a example of sampling from Chi Square with 40 Degrees of Freedom:
from scipy import stats
import numpy as np
import matplotlib.pyplot as plt
rv = stats.chi2(40)
N = 200000
X = rv.rvs(size=N, random_state=1)
fig, axe = plt.subplots()
n, bins, patches = axe.hist(X, 50, normed=1, facecolor='green', alpha=0.75)
plt.show(axe)
It leads to:

How do you quantize a simple input using python

I am using the below codes to quantise the input signal for quantisation interval of 0.5 and this should give me staircase signal.The algorithm used here is same as used in Simulink.Could any one help me plot the quantised signal.
import numpy as np
import matplotlib.pyplot as plt
for i in range(0,10):
q=0.5;
x=q*np.round(i/q);
plt.plot(i,x)
plt.xlim([0,10])
plt.ylim([0,10])
plt.hold()
plt.grid()
plt.show()
Do you mean something like this?
import numpy as np
import matplotlib.pyplot as plt
q = 0.5
x = np.linspace(0, 10, 1000)
y = q * np.round(x/q)
plt.plot(x,y)

Categories