import numpy as np
import matplotlib.pyplot as plt
size=10
x=np.arange(size)
y=np.where(x%2==0,1,0)
fig,ax=plt.subplots(figsize=(6,4))
plt.plot(x,y,marker='o',linestyle='-',color='orange',markersize=8,linewidth=2)
ax.set_xlim(-1,size)
ax.set_ylim(-0.5,1.5)
ax.set_xticks([])
ax.set_yticks([])
ax.set_frame_on(False)
plt.title('Zig zag pattern plot')
plt.show()
#source code --> clcoding.com
Code Explanation:
1. Import Required Libraries
import numpy as np
import matplotlib.pyplot as plt
numpy is used to generate numerical arrays.
matplotlib.pyplot is used to create and display the zigzag plot.
2. Define the Number of Zigzag Points
size = 10 # Change this for more or fewer zigzags
The variable size determines the number of points in the zigzag pattern.
Increasing this value makes the zigzag longer.
3. Create X and Y Coordinates
x = np.arange(size) # X coordinates (0,1,2,...)
y = np.where(x % 2 == 0, 1, 0) # Alternate Y values (1, 0, 1, 0, ...)
x = np.arange(size) generates an array [0, 1, 2, ..., size-1], representing evenly spaced x-coordinates.
y = np.where(x % 2 == 0, 1, 0) assigns alternating y values:
If x is even, y = 1 (peak).
If x is odd, y = 0 (valley).
This creates the zigzag effect.
Example of x and y values for size = 10:
x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
y = [1, 0, 1, 0, 1, 0, 1, 0, 1, 0]
4. Create the Figure and Axis
fig, ax = plt.subplots(figsize=(6, 4))
plt.subplots() creates a figure (fig) and an axis (ax).
figsize=(6,4) makes the plot 6 inches wide and 4 inches tall.
5. Plot the Zigzag Pattern
plt.plot(x, y, marker='o', linestyle='-', color='b', markersize=8, linewidth=2)
plt.plot(x, y, ...) plots the zigzag pattern.
marker='o' adds circular markers at each point.
linestyle='-' connects the points with a solid line.
color='b' makes the line blue.
markersize=8 controls the size of the circles.
linewidth=2 makes the line thicker.
6. Adjust the Axis for a Clean Look
ax.set_xlim(-1, size)
ax.set_ylim(-0.5, 1.5)
ax.set_xlim(-1, size): Ensures the x-axis starts a little before 0 and ends at size.
ax.set_ylim(-0.5, 1.5): Ensures the y-axis has enough space above and below the zigzag.
ax.set_xticks([])
ax.set_yticks([])
ax.set_frame_on(False)
ax.set_xticks([]): Removes x-axis tick marks.
ax.set_yticks([]): Removes y-axis tick marks.
ax.set_frame_on(False): Hides the frame for a clean look.
7. Display the Plot
plt.show()
Displays the zigzag pattern.
0 Comments:
Post a Comment