import numpy as np
import matplotlib.pyplot as plt
k=8
theta=np.linspace(0,2*np.pi,300)
phi=np.linspace(0,np.pi,300)
theta,phi=np.meshgrid(theta,phi)
r = np.sin(k * theta) * np.sin(phi)
x = r * np.sin(phi) * np.cos(theta)
y = r * np.sin(phi) * np.sin(theta)
z = r * np.cos(phi)
fig=plt.figure(figsize=(6,6))
ax=fig.add_subplot(111,projection='3d')
surf=ax.plot_surface(x,y,z,cmap='inferno',edgecolor='none')
ax.set_title('3D Rose Surface Plot')
ax.axis('off')
plt.show()
#source code --> clcoding.com
Code Explanation:
1. Import Libraries
import numpy as np
import matplotlib.pyplot as plt
numpy: For numerical calculations and creating
coordinate grids.
matplotlib.pyplot: For plotting the 3D surface.
2. Set the Parameter
k = 5 #
Number of petals (can be any float or integer)
The variable k controls the number of
"petals" in the rose pattern.
A higher or fractional k gives more complex shapes.
3. Create Meshgrid for Angles
theta = np.linspace(0, 2 * np.pi, 300) # Azimuthal angle
phi = np.linspace(0, np.pi, 300) # Polar angle
theta, phi = np.meshgrid(theta, phi)
theta: Goes from 0 to
2π, wrapping around the z-axis (like longitude).
phi: Goes from 0 to
π, spanning from top to bottom of the sphere (like
latitude).
np.meshgrid creates a grid of angle values used for
surface plotting.
4. Define the Rose Function
r = np.sin(k * theta) * np.sin(phi)
This defines the radius r at each angle based on the
polar rose formula:
r(θ,ϕ)=sin(kθ)⋅sin(ϕ)
sin(kθ) makes the petal pattern.
sin(φ) ensures the pattern wraps over the sphere rather than staying flat.
5. Convert to 3D Cartesian Coordinates
x = r * np.sin(phi) * np.cos(theta)
y = r * np.sin(phi) * np.sin(theta)
z = r * np.cos(phi)
This converts spherical coordinates
(r,θ,ϕ) to Cartesian coordinates (x,y,z):
x=r⋅sin(ϕ)⋅cos(θ)
y=r⋅sin(ϕ)⋅sin(θ)
z=r⋅cos(ϕ)
This gives a 3D shape based on the rose function wrapped over a sphere.
6. Plot the Surface
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')
surf = ax.plot_surface(x, y, z, cmap='inferno',
edgecolor='none')
Creates a 3D plot (projection='3d').
plot_surface() draws the rose surface using x, y, z.
cmap='inferno' adds color based on height/intensity.
edgecolor='none' smooths the surface by hiding grid lines.
7. Final Touches
ax.set_title(f"3D Rose Surface Plot (k =
{k})")
ax.axis('off')
plt.show()
Adds a title showing the value of k.
Turns off axis for a clean visual.