How To 3D Plot Function Of 2 Variables In Python?
Solution 1:
If you're using numpy
, then don't use the math
module. Numpy as all of the math functions built in but they work on numpy arrays far better. We can calculate nu at all of our b, d values with the aid of a meshgrid.
A meshgrid can take 2 1D arrays, and return 2 2D arrays such that every index in the arrays corresponds to a unique pair of elements from the original 1D arrays.
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
b = np.arange(0.2, 3.2, 0.2)
d = np.arange(0.1, 1.0, 0.1)
B, D = np.meshgrid(b, d)
nu = np.sqrt( 1 + (2*D*B)**2 ) / np.sqrt( (1-B**2)**2 + (2*D*B)**2)
fig = plt.figure()
ax = Axes3D(fig)
ax.plot_surface(B, D, nu)
plt.xlabel('b')
plt.ylabel('d')
plt.show()
Additionally, 3D plots tend to block seeing all of the data (because a spike hides things behind it). I would recommend a pcolormesh or a contourf plot. In the later case the last 6 lines become:
plt.contourf(B, D, nu)
plt.colorbar()
plt.xlabel('b')
plt.ylabel('d')
plt.show()
Solution 2:
This should work: I'm not a Python expert and especially the two for loops might be very unpythonic, but it gets the job done.
import math
import matplotlib.pyplot as plt
import numpy as np
b = np.arange(0.2, 3.2, 0.2)
d = np.arange(0.1, 1.0, 0.1)
nu = np.zeros( (b.size, d.size) )
counter_y = 0
for deta in d:
counter_x = 0
for beta in b:
nu[counter_x, counter_y] = math.sqrt( 1 + (2*deta*beta)**2 ) / math.sqrt( (1-beta**2)**2 + (2*deta*beta)**2)
counter_x += 1
counter_y += 1
X, Y = np.meshgrid(d, b)
fig = plt.figure()
ax = fig.add_subplot(111, projection = '3d')
ax.plot_surface(X, Y, nu)
Solution 3:
what you need is to first create a matplotlib figure
.
fig = plt.figure()
ax = Axes3D(fig)
ax.plot(b, d, nu)
plt.show()
Further, all your variable should be of same size. So, your variable d
should be an array of same length as the others.
If you turn your variable d
into array of 0.1
of length 510
as others, you get following.
import math
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
nu = []
b = [0.1 + i / 100 for i in range(0, 510)]
d = 0.1
for beta in b:
nu.append( math.sqrt(1+(2*d*beta)**2)/ math.sqrt((1-beta**2)**2+(2*d*beta)**2))
#turned d into array of length 510 with 0.1 for each value
d = np.ones(510)*0.1
fig = plt.figure()
ax = Axes3D(fig)
ax.plot(b, d, nu)
plt.show()
you get:
Post a Comment for "How To 3D Plot Function Of 2 Variables In Python?"