import numpy as np
import matplotlib.pyplot as plt
t=np.linspace(0,2*np.pi,500)
x=16*np.sin(t)**3
y=13*np.cos(t)-5*np.cos(2*t)-2*np.cos(3*t)-np.cos(4*t)
plt.figure(figsize=(6,6))
plt.plot(x,y,color='red',linewidth=8)
plt.title("heartshape pattern plot",fontsize=14)
plt.axis("equal")
plt.axis("off")
plt.show()
#source code --> clcoding.com
Code Explanation:
Step 1: Importing Required Libraries
import numpy as np
import matplotlib.pyplot as plt
NumPy (np): Used to create numerical arrays and perform mathematical operations efficiently.
Matplotlib (plt): A powerful plotting library that allows visualization of data in various formats.
Step 2: Creating the Parameter t
t = np.linspace(0, 2 * np.pi, 500)
The variable t is an array of 500 evenly spaced values between 0 and 2π.
This range is crucial because it allows the parametric equations to fully define the heart shape. More points would create a smoother curve, while fewer points would make it look more jagged.
Step 3: Defining the Heart Shape Equations
x = 16 * np.sin(t)**3
y = 13 * np.cos(t) - 5 * np.cos(2*t) - 2 * np.cos(3*t) - np.cos(4*t)
These equations define the x and y coordinates of the heart shape.
Explanation of the x Equation:
x = 16 * np.sin(t)**3
np.sin(t) generates a sine wave between -1 and 1.
Cubing it (**3) amplifies the curvature and ensures the heart shape is symmetric.
The factor 16 scales the shape horizontally.
Explanation of the y Equation:
y = 13 * np.cos(t) - 5 * np.cos(2*t) - 2 * np.cos(3*t) - np.cos(4*t)
The primary component is 13 * np.cos(t), which determines the general height and shape.
The additional cosine terms (cos(2t), cos(3t), cos(4t)) refine the shape, adding the necessary dips and curves to resemble a heart.
The coefficients (13, -5, -2, -1) adjust the proportions of the lobes and the bottom curve.
Step 4: Plotting the Heart
plt.figure(figsize=(6, 6))
plt.plot(x, y, color='red', linewidth=8)
plt.figure(figsize=(6,6)): Creates a square figure (6x6 inches) to ensure the heart doesn’t look distorted.
plt.plot(x, y, color='red', linewidth=8):
Plots the heart shape using the x and y coordinates.
The color is set to red to resemble a traditional heart.
The linewidth is set to 8, making the heart bold and thick.
Step 5: Customizing the Display
plt.title("Heart shape pattern plot", fontsize=16)
plt.axis("equal")
plt.axis("off")
plt.title("Heart shape pattern plot", fontsize=16): Adds a title to the plot with a larger font size for visibility.
plt.axis("equal"): Ensures the aspect ratio remains 1:1, preventing distortion.
plt.axis("off"): Hides the axes, making the heart the only focus.
Step 6: Displaying the Heart
plt.show()
This renders the heart shape and displays it on the screen.
0 Comments:
Post a Comment