import matplotlib.pyplot as plt
import numpy as np
x,y=np.meshgrid(np.arange(0,10,1),np.arange(0,10,1))
x=x.flatten()
y=y.flatten()
plt.figure(figsize=(6,6))
plt.scatter(x,y,s=100,c='blue',edgecolor='black')
plt.axis('equal')
plt.grid(True,linestyle='--',alpha=0.5)
plt.title('Lattice pattern plot')
plt.show()
#source code --> clcoding.com
Code Explanation:
1. Import Necessary Libraries
import matplotlib.pyplot as plt
import numpy as np
Matplotlib is used for visualization.
NumPy is used for numerical computations.
2. Create a Grid of Points
x, y = np.meshgrid(np.arange(0, 10, 1), np.arange(0, 10, 1))
np.arange(0, 10, 1) generates values from 0 to 9 (step = 1).
np.meshgrid() creates a 2D grid from these values:
x contains column values (repeats horizontally).
y contains row values (repeats vertically).
Example Output of np.meshgrid()
If np.arange(0, 3, 1) is used instead of 0 to 10, it would generate:
x =
[[0 1 2]
[0 1 2]
[0 1 2]]
y =
[[0 0 0]
[1 1 1]
[2 2 2]]
This represents a grid of points at (0,0), (1,0), (2,0), (0,1), (1,1), (2,1), etc.
3. Flatten the Grid into 1D Arrays
x = x.flatten()
y = y.flatten()
.flatten() converts the 2D grid into 1D arrays of x and y coordinates.
Now, we have all grid points in a simple list format for plotting.
4. Create the Scatter Plot
plt.figure(figsize=(6,6))
figsize=(6,6) ensures a square figure to maintain equal spacing.
plt.scatter(x, y, s=100, c='blue', edgecolor='black')
plt.scatter(x, y, s=100, c='blue', edgecolor='black')
Plots blue dots (c='blue').
Each dot has a size of 100 (s=100).
A black border (edgecolor='black') surrounds each dot.
5. Adjust the Plot Formatting
plt.axis('equal')
Ensures both x and y axes have the same scale, preventing distortion.
plt.grid(True, linestyle='--', alpha=0.5)
Enables grid lines (plt.grid(True)) for better visualization.
Dashed grid lines (linestyle='--').
alpha=0.5 makes the grid lines slightly transparent.
plt.title('Lattice pattern plot')
Sets the title of the plot.
6. Display the Plot
plt.show()
Displays the final lattice pattern.
0 Comments:
Post a Comment