import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
theta = np.linspace(0, 2 * np.pi, 100)
z = np.linspace(-2, 2, 100)
theta, z = np.meshgrid(theta, z)
r = z**2 + 1
x = r * np.sin(theta)
y = r * np.cos(theta)
fig = plt.figure(figsize=(12, 8))
ax = fig.add_subplot(111, projection='3d')
colors = np.sin(z) * np.cos(theta)
surf = ax.plot_surface(x,y,z,facecolors=plt.cm.viridis((colors - colors.min()) /
(colors.max() - colors.min())), rstride=1, cstride=1, antialiased=True)
ax.set_xlabel('X Axis')
ax.set_ylabel('Y Axis')
ax.set_zlabel('Z Axis')
ax.set_title('Stellar Spectrum Mesh: 3D Waveform using Matplotlib')
plt.colorbar(surf, shrink=0.5, aspect=5)
plt.show()
#source code --> clcoding.com
Code Explanation:
1. Importing Libraries
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
numpy (np): Used for numerical operations, creating
arrays, and mathematical functions.
2. Create Data for the Mesh Grid
a) Generate Angles (Theta) and Z Values
theta = np.linspace(0, 2 * np.pi, 100)
z = np.linspace(-2, 2, 100)
np.linspace(start, stop, num):
b) Create a Mesh Grid
theta, z = np.meshgrid(theta, z)
np.meshgrid():
3. Calculate Radius and Coordinates
a) Calculate Radius (r)
r = z**2 + 1
r=z 2+1
This results in a wavy, expanding, circular mesh.
b) Compute X and Y Coordinates
x = r * np.sin(theta)
y = r * np.cos(theta)
X and Y Coordinates:
x = r × sin(θ) and y = r × cos(θ) are parametric
equations for a circular shape.
The radius r scales the size of the circle, and
theta controls the angular position.
The expanding radius forms a spiral effect.
4. Plot the 3D Surface
a) Initialize the Figure and Axis
fig = plt.figure(figsize=(12, 8))
ax = fig.add_subplot(111, projection='3d')
fig = plt.figure(figsize=(12, 8)):
Creates a figure of size 12x8 inches.
ax = fig.add_subplot(111, projection='3d'):
Creates a 3D axis using projection='3d'.
111 indicates 1 row, 1 column, and first subplot.
5. Apply Colors Using a Spectrum
a)Generate Color Values
colors = np.sin(z) * np.cos(theta)
This applies a color effect using a mathematical
combination of sine and cosine.
surf = ax.plot_surface(
x, y, z,
facecolors=plt.cm.viridis((colors - colors.min()) / (colors.max() -
colors.min())),
rstride=1,
cstride=1,
antialiased=True
)
ax.plot_surface():
6. Customize the Plot
a) Add Axis Labels and Title
ax.set_xlabel('X Axis')
ax.set_ylabel('Y Axis')
ax.set_zlabel('Z Axis')
ax.set_title('Stellar Spectrum Mesh: 3D Waveform
using Matplotlib')
Labels the axes for clarity.
plt.colorbar(surf, shrink=0.5, aspect=5)
plt.colorbar():
7. Display the Plot
plt.show()
This function renders and displays the plot.
0 Comments:
Post a Comment