Sunday, 6 April 2025

Stellar Spectrum Mesh Grid Pattern using Python

 


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.

 matplotlib.pyplot (plt): Used for plotting 2D and 3D visualizations.

 mpl_toolkits.mplot3d: Provides tools for 3D plotting using Matplotlib.

 Axes3D: Enables 3D plotting capabilities.

 

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):

 Generates 100 evenly spaced values.

 theta ranges from 0 to 2π, representing a full circular rotation in radians.

 z ranges from -2 to 2, representing the vertical axis.

 

b) Create a Mesh Grid

theta, z = np.meshgrid(theta, z)

np.meshgrid():

 Creates a 2D grid of coordinates from theta and z.

 Every combination of theta and z is represented in a matrix form.

 Used for surface plotting.

 

3. Calculate Radius and Coordinates

a) Calculate Radius (r)

r = z**2 + 1

r=z 2+1

 The radius expands as z moves away from zero.

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.

 np.sin(z) creates a wave pattern along the Z-axis.

 np.cos(theta) creates variations based on angular position.

 Multiplying them results in a dynamic, swirling color effect.

 b) Plot the Surface with Colors

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():

 Plots a 3D surface using the computed X, Y, and Z coordinates.

 facecolors applies a gradient from the Viridis colormap (plt.cm.viridis).

 This ensures color values are scaled between 0 and 1.

 rstride=1 and cstride=1 determine the resolution of the mesh by setting row and column strides.

 antialiased=True smoothens the surface edges.

 

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.

 The title provides a meaningful description of the plot.

 b) Add a Colorbar

plt.colorbar(surf, shrink=0.5, aspect=5)

plt.colorbar():

 Adds a colorbar to represent the color mapping on the surface.

 shrink=0.5: Adjusts the colorbar size to 50% of its original size.

 aspect=5: Adjusts the aspect ratio of the colorbar for better readability.

 

7. Display the Plot

plt.show()

This function renders and displays the plot.

 


Related Posts:

0 Comments:

Post a Comment

Popular Posts

Categories

100 Python Programs for Beginner (98) AI (41) Android (24) AngularJS (1) Api (2) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (199) C (77) C# (12) C++ (83) Course (67) Coursera (251) Cybersecurity (25) Data Analysis (3) Data Analytics (3) data management (11) Data Science (149) Data Strucures (8) Deep Learning (21) Django (16) Downloads (3) edx (2) Engineering (14) Euron (29) Events (6) Excel (13) Factorial (1) Finance (6) flask (3) flutter (1) FPL (17) Generative AI (11) Google (36) Hadoop (3) HTML Quiz (1) HTML&CSS (47) IBM (30) IoT (1) IS (25) Java (93) Java quiz (1) Leet Code (4) Machine Learning (86) Meta (22) MICHIGAN (5) microsoft (4) Nvidia (4) Pandas (4) PHP (20) Projects (29) pyth (1) Python (1057) Python Coding Challenge (461) Python Quiz (128) Python Tips (5) Questions (2) R (70) React (6) Scripting (3) security (3) Selenium Webdriver (4) Software (17) SQL (42) UX Research (1) web application (8) Web development (4) web scraping (2)

Followers

Python Coding for Kids ( Free Demo for Everyone)