Python3 [Jupyter] code is not showing data on graph [duplicate] - python

This question already has an answer here:
try plotting an iteration but plt.plot is empty
(1 answer)
Closed 4 years ago.
I'm sure this question has been asked numerous times before but alas I cannot find the correct answer. I'm trying to plot really simple code however when it executes the final result is just an empty graph. Code below:
import math
import matplotlib.pyplot as mpl
import numpy as np
Q = 13.6
m_e = 9.11e-31
k = 8.6e-5
c = 3e8
eta = 4e-10
for T in np.arange(3000,4500):
S = 3.84*eta*((k*T)/(m_e*c**2))**(3/2)*(Q/(k*T))
X = (-1 + np.sqrt(1+(4*S)))/(2*S)
%matplotlib inline
mpl.plot(S, T)
mpl.show()
I realise that is the way with code it's probably a very trivial answer but I can't find the problem. Thanks in advance for any help!

You are not doing anything with the values you create in the for loop. Therefore, when you come to plot, you just have 1 value of S and X and T, therefore, your graph will be empty.
One way to fix this would be to append the values into a list which you can then pass to a call to plot:
Q = 13.6
m_e = 9.11e-31
k = 8.6e-5
c = 3e8
eta = 4e-10
S_list = []
X_list = []
for T in np.arange(3000,4500):
S = 3.84*eta*((k*T)/(m_e*c**2))**(3/2)*(Q/(k*T))
X = (-1 + np.sqrt(1+(4*S)))/(2*S)
S_list.append(S)
X_list.append(X)
I'm not sure if you actually want to plot the values of S against T, but if you do, then you would do something like:
mpl.plot(S_list, np.arange(3000,4500))
mpl.show()
Which gives something like:
Edit:
You don't actually need to do any loops here, numpy can handle the complete calculation:
T = np.arange(3000,4500)
S = 3.84*eta*((k*T)/(m_e*c**2))**(3/2)*(Q/(k*T))
X = (-1 + np.sqrt(1+(4*S)))/(2*S)
mpl.plot(S, T)
mpl.show()
Would give you the same figure

S, X and T are all scalar. I am assuming you want to plot a vector against vector.
I think you are trying to do this:
import math
import matplotlib.pyplot as mpl
import numpy as np
Q = 13.6
m_e = 9.11e-31
k = 8.6e-5
c = 3e8
eta = 4e-10
S=[]
X=[]
for T in np.arange(3000,4500):
tmp=3.84*eta*((k*T)/(m_e*c**2))**(3/2)*(Q/(k*T))
S.append(tmp)
X.append((-1 + np.sqrt(1+(4*tmp)))/(2*tmp))
%matplotlib inline
mpl.plot(S, X)
mpl.show()

import math
import matplotlib.pyplot as mpl
import numpy as np
Q = 13.6
m_e = 9.11e-31
k = 8.6e-5
c = 3e8
eta = 4e-10
x=[]
t=[]
for T in np.arange(3000,4500):
S = 3.84*eta*((k*T)/(m_e*c**2))**(3/2)*(Q/(k*T))
X = (-1 + np.sqrt(1+(4*S)))/(2*S)
x.append(X)
t.append(T)
mpl.plot(x,t)
mpl.show()

Related

Arithmetic operations using list

I am trying to write a MATLAB code into python. The original MATLAB code is from this following vid: https://www.youtube.com/watch?v=T97ddyTMuro. Briefly, the MATLAB code is as follows:
v = 10;
theta = linspace(15, 75, 100);
g = 9.81;
t = 2*v*sin(theta)/g;
r = v*cos(theta).*t;
plot(r,theta)
I was trying to recreate this code in python, attached herewith is what I have tried and failed:
import numpy as np
import math as m
import matplotlib.pyplot as plt
theta = np.linspace(0,70,100)
v = 10 # velocity (m/s)
g = 9.81 # accel. due to grav.
t = []
r = []
a = []
multi =[]
for i in np.linspace(0,70,100):
t.append(2*v*(m.sin(np.deg2rad(i)))/g)
for j in np.linspace(0,70,100):
r.append(v*(m.cos(np.deg2rad(i))))
a.append(r[j]*t[j])
Unable to multiply two lists as they are not integers.
An easier approach is to directly use only numpy code:
import numpy as np
import matplotlib.pyplot as plt
theta = np.deg2rad(np.linspace(0,70,100))
v = 10 # velocity (m/s)
g = 9.81 # accel. due to grav.
t1 = 2*v*np.sin(theta)/g
r = v*np.cos(theta)*t1 # will compute elementwise multiplication
plt.plot(r, theta)
plt.show()

I am getting two plots for one data set in python

I am working through example 8.1 titled Euler's Method from Mark Newman's book Computational Physics. I rewrote the example as a method with Numpy arrays but when I plot it I get two plots on the same figure not sure how to correct it. Also is there better way to convert my 2 1D arrays into 1 2D array to use for plotting in Matplotlib, thanks.
Newman's example :
from math import sin
from numpy import arange
from pylab import plot,xlabel,ylabel,show
def f(x,t):
return -x**3 + sin(t)
a = 0.0 # Start of the interval
b = 10.0 # End of the interval
N = 1000 # Number of steps
h = (b-a)/N # Size of a single step
x = 0.0 # Initial condition
tpoints = arange(a,b,h)
xpoints = []
for t in tpoints:
xpoints.append(x)
x += h*f(x,t)
plot(tpoints,xpoints)
xlabel("t")
ylabel("x(t)")
show()
My modifications:
from pylab import plot,show,xlabel,ylabel
from numpy import linspace,exp,sin,zeros,vstack,column_stack
def f(x,t):
return (-x**(3) + sin(t))
def Euler(f,x0,a,b):
N=1000
h = (b-a)/N
t = linspace(a,b,N)
x = zeros(N,float)
y = x0
for i in range(N):
x[i] = y
y += h*f(x[i],t[i])
return column_stack((t,x)) #vstack((t,x)).T
plot(Euler(f,0.0,0.0,10.0))
xlabel("t")
ylabel("x(t)")
show()
The reason you get two lines is that t as well as x are plotted against their index, instead of x plotted against t
I don't see why you'd want to stack the two arrays. Just keep then separate, which will also solve the problem of the two plots.
The following works fine.
import numpy as np
import matplotlib.pyplot as plt
f = lambda x,t: -x**3 + np.sin(t)
def Euler(f,x0,a,b):
N=1000
h = (b-a)/N
t = np.linspace(a,b,N)
x = np.zeros(N,float)
y = x0
for i in range(N):
x[i] = y
y += h*f(x[i],t[i])
return t,x
t,x = Euler(f,0.0,0.0,10.0)
plt.plot(t,x)
plt.xlabel("t")
plt.ylabel("x(t)")
plt.show()

Find an Inverse for the Exponential Integral function

I have a program where I have to find x.
But I have to use the special function Ei - the exponential integral, and x is inside the argument of Ei.
So Python isn't recognizing it.
ei(mx) = te^r + ei(c)
Here the RHS is a constant alongwith m.
I want to find the value of x, and then append it to a list. But Python isn't able to do this.
from scipy import special
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
Y = []
X = np.arange(0,10,.1)
for i in X:
y = scipy.special.expi(i)
Y.append(y)
N_0 = 2
t_f = 100
r = 2
K = 100
N_t = [N_0,]
t = np.arange(0,100,1)
for i in t:
l = i*e**r + scipy.special.expi(r*N_t[i]/K)
N_t.append(l)
plt.plot(X,Y)
plt.plot(t,N_t)
plt.show
I've corrected some mistakes in your code to give the following. You should compare this with your code line by line.
from scipy.special import expi
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
Y = []
X = np.arange(0,10,.1)
for i in X:
y = expi(i)
Y.append(y)
N_0 = 2
t_f = 100
r = 2
K = 100
N_t = [N_0,]
t = np.arange(0,100,1)
for i in t:
l = i*np.exp(r) + expi(r*N_t[i]/K)
N_t.append(l)
plt.plot(X,Y)
plt.plot(t,N_t)
plt.show()
However, there is still one possible flaw that I notice and can't resolve. You plot X and t together in the same graph at the end yet X ranges over 0 to 10 and t ranges over 0 to 100. Is this what you intended?
Also matplotlib complains that the lengths of the vectors supplied to it in the second call to plot are not the same.

Draw a specific function in Python

I need to draw a graph in python using this function:
b²x²+a²z²+2dxz²+d²z²-a²b²=0
where b, a and d will be different each time.
The problem here for me is that I cannot separate X and Z. I've tried something like that.
import numpy as np
import matplotlib.pyplot as plt
z = -np.linspace(9,15,100)
x = np.linspace(-26,26,1000)
x,z = np.meshgrid(x,z)
a = 4
b = 2
d = 1
Z = a**2*z**2+2*d*z**2-a**2*b**2
X = b**2*x**2
plt.contour(x,z,(X+Z),[0])
plt.xlim([-1.5,1.5])
plt.ylim([-11.5,-8.5])
I don't know if matplotlib can create an implicit plot; a quick search of their documentation didn't turn up anything. But it appears you can use Sympy for that. From this SO question:
from sympy import var, Plot
var('x y')
Plot(x*y**3 - y*x**3)
Working code here:
from functools import partial
import numpy
import scipy.optimize
import matplotlib.pyplot as pp
a = 4
b = 3
d = 0.6
def z(x, y):
return b**2*x**2+a**2*y**2+2*d*x*y**2+d**2*y**2-a**2*b**2
x_window = 0, 5
y_window = 0, 5
xs = []
ys = []
for x in numpy.linspace(*x_window, num=200):
try:
# A more efficient technique would use the last-found-y-value as a
# starting point
y = scipy.optimize.brentq(partial(z, x), *y_window)
except ValueError:
# Should we not be able to find a solution in this window.
pass
else:
xs.append(x)
ys.append(y)
pp.plot(xs, ys)
pp.xlim(*x_window)
pp.ylim(*y_window)
pp.show()

Python -- sympy solve() returning another equation instead of value

This creates a list of points and the sympy solve() method should be returning the value of x. Instead it's returning yet another equation, and I'm not sure why. The ogrid() and ravel() are creating a list of points in the plot and this is on Matplotlib, if that makes a difference but I don't think it should. It should be finding root(s) of the equation. I'm not sure what I'm doing wrong here that causes it to not return a value, but instead returns another equation:
from mpl_toolkits.axes_grid.axislines import SubplotZero
from pylab import *
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.path import Path
import matplotlib.patches as patches
from matplotlib import rc
import random
from sympy.solvers import solve
from sympy import *
a = -2; b = 1
y, x = np.ogrid[-10:10:100j, -10:10:100j]
xlist = x.ravel(); ylist = y.ravel()
elliptic_curve = pow(y, 2) - pow(x, 3) - x * a - b
plt.contour(xlist, ylist, elliptic_curve, [0])
randmid = random.randint(30,70)
#y = ylist[randmid]; x = xlist[randmid]
xsym, ysym = symbols('x ylist[randmid]')
x_result = solve(pow(ysym, 2) - pow(xsym, 3) - xsym * a - b, xsym) # 11/5/13 needs to return a value
I'm teaching myself Python so this is probably something a junior programmer can help me out with, but if a pro sees this and can spare a moment to help that'd be great.
EDIT:
Returns a value for y roughly 3.xx where there's not 3 possible x-values:
x_result is a list of expressions, which is the solutions of your equation. It's not a list of value because ysym is a symbol. If you want the numeric results, you need call subs() and evalf():
[e.subs({ysym:ylist[randmid]}).evalf() for e in x_result]
output:
[0.0871073310916539 - 8.0e-17*I,
1.36864647418387 + 4.37e-17*I,
-1.45575380527552 + 3.63e-17*I]

Categories

Resources