Sunday, 2 March 2025

Concentric circle plot using python




import numpy as np
import matplotlib.pyplot as plt

fig,ax=plt.subplots(figsize=(6,6))
num_circles=10
radii=np.linspace(0.2,2,num_circles)
for r in radii:
    circle=plt.Circle((0,0),r,color='b',fill=False,linewidth=2)
    ax.add_patch(circle)

ax.set_xlim(-2.5,2.5)
ax.set_ylim(-2.5,2.5)
ax.set_aspect('equal')
ax.set_xticks([])
ax.set_yticks([])
ax.spines['top'].set_visible(False)
ax.spines['bottom'].set_visible(False)
ax.spines['left'].set_visible(False)
ax.spines['right'].set_visible(False)
plt.title("Concentric circle plot")
plt.show()

#source code --> clcoding.com 

Code Explanation:

1. Import Required Libraries

import matplotlib.pyplot as plt

import numpy as np

matplotlib.pyplot: The core library for creating visualizations.

numpy: Used to generate evenly spaced values for the circle radii.


2. Create the Figure and Axis

fig, ax = plt.subplots(figsize=(6, 6))

fig, ax = plt.subplots() creates a figure (fig) and an axis (ax), which we use to draw our circles.

figsize=(6,6) ensures the figure is a square, keeping the circles proportionate.


3. Define the Circles

num_circles = 10  # Number of concentric circles

radii = np.linspace(0.2, 2, num_circles)  # Generate 10 radius values between 0.2 and 2

num_circles = 10: We want 10 circles.

np.linspace(0.2, 2, num_circles):

Generates 10 values between 0.2 (smallest circle) and 2 (largest circle).

These values represent the radii of the circles.


4. Draw Each Circle

for r in radii:

    circle = plt.Circle((0, 0), r, color='b', fill=False, linewidth=2)  # Blue hollow circles

    ax.add_patch(circle)

We loop through each radius in radii:

plt.Circle((0, 0), r, color='b', fill=False, linewidth=2):

(0,0): Sets the center at the origin.

r: Defines the radius of the circle.

color='b': Blue (b) outline color.

fill=False: Ensures only the outline is drawn, not a solid circle.

linewidth=2: Sets the thickness of the circle outline.

ax.add_patch(circle): Adds the circle to the plot.


5. Adjust the Plot

ax.set_xlim(-2.5, 2.5)

ax.set_ylim(-2.5, 2.5)

ax.set_aspect('equal')  # Ensures circles are perfectly round

ax.set_xlim(-2.5, 2.5) / ax.set_ylim(-2.5, 2.5):

Expands the plot’s limits slightly beyond the largest circle (radius 2).

ax.set_aspect('equal'):

Prevents distortion by ensuring equal scaling on both axes.


6. Hide Axes for a Clean Look

ax.set_xticks([])

ax.set_yticks([])

ax.spines['top'].set_visible(False)

ax.spines['right'].set_visible(False)

ax.spines['left'].set_visible(False)

ax.spines['bottom'].set_visible(False)

ax.set_xticks([]) / ax.set_yticks([]): Removes tick marks from the plot.

ax.spines[...]: Hides the border lines around the plot.


7. Display the Plot

plt.show()

plt.show() renders and displays the plot.


Pentagonal grid pattern plot using python

 


import matplotlib.pyplot as plt

import numpy as np

def draw_pentagon(ax,center,size):

    angles=np.linspace(0,2*np.pi,6)[:-1]+np.pi/10

    x=center[0]+size*np.cos(angles)

    y=center[1]+size*np.sin(angles)

    ax.plot(np.append(x,x[0]),np.append(y,y[0]),'b')

def draw_five_pentagons(size=1.0):

    fig,ax=plt.subplots(figsize=(8,8))

    positions=[(0,0),(1.5*size,0),(-1.5*size,0),(0.75*size,np.sqrt(3)*size),(-0.75*size,np.sqrt(3)*size)]

    for pos in positions:

        draw_pentagon(ax,pos,size)

 ax.set_aspect('equal')

    ax.axis('off')

    plt.title('Pentagonal grid pattern plot')

    plt.show()

draw_five_pentagons()

#source code --> clcoding.com 


Code Explanation:

Imports

import matplotlib.pyplot as plt

import numpy as np

matplotlib.pyplot → Used for plotting the pentagons.

numpy → Used for numerical calculations, particularly for computing pentagon vertices.

Function: draw_pentagon

def draw_pentagon(ax, center, size):

    """Draws a pentagon given a center and size."""

Defines a function draw_pentagon that takes:

ax: Matplotlib axes where the pentagon will be drawn.

center: Coordinates (x, y) where the pentagon is placed.

size: The radius or size of the pentagon.


    angles = np.linspace(0, 2 * np.pi, 6)[:-1] + np.pi / 10

np.linspace(0, 2 * np.pi, 6) → Generates 6 equally spaced angles from 0 to 

2ฯ€ (full circle).

[:-1] → Removes the last element to keep only 5 points (for a pentagon).

+ np.pi / 10 → Rotates the pentagon slightly for proper orientation.


    x = center[0] + size * np.cos(angles)

    y = center[1] + size * np.sin(angles)

Computes the x and y coordinates of the pentagon vertices using trigonometric functions:

np.cos(angles) → Calculates the x-coordinates.

np.sin(angles) → Calculates the y-coordinates.


    ax.plot(np.append(x, x[0]), np.append(y, y[0]), 'b')

np.append(x, x[0]) → Ensures the first and last points are connected to close the pentagon.

ax.plot(..., 'b') → Plots the pentagon outline with a blue ('b') color.


Function: draw_five_pentagons

def draw_five_pentagons(size=1.0):

    """Draws exactly five pentagons."""

Defines a function to draw exactly five pentagons with a given size.


    fig, ax = plt.subplots(figsize=(8, 8))

Creates a figure (fig) and axes (ax) with a size of 8×8 inches.


    positions = [(0, 0), (1.5 * size, 0), (-1.5 * size, 0), 

                 (0.75 * size, np.sqrt(3) * size), (-0.75 * size, np.sqrt(3) * size)]

Defines five fixed positions where pentagons will be placed:

(0, 0) → Center pentagon.

(±1.5 * size, 0) → Left and right pentagons.

(±0.75 * size, np.sqrt(3) * size) → Two pentagons above.


    for pos in positions:

        draw_pentagon(ax, pos, size)

Iterates through the positions list and calls draw_pentagon(ax, pos, size) to draw each pentagon.

    ax.set_aspect('equal')

Ensures equal scaling so the pentagons do not appear distorted.


    ax.axis('off')

Hides the x and y axes for a cleaner visual appearance.


    plt.title("Pentagon grid pattern plot")


Sets a title for the plot.

    plt.show()

Displays the final pentagon plot.


Diamond outline pattern plot

 


import numpy as np

import matplotlib.pyplot as plt

diamond_x=[0,1,0,-1,0]

diamond_y=[1,0,-1,0,1]

plt.figure(figsize=(5,5))

plt.plot(diamond_x,diamond_y,'b-',linewidth=2)

plt.xlim(-1.5,1.5)

plt.ylim(-1.5,1.5)

plt.axhline(0,color='gray',linestyle='--',linewidth=0.5)

plt.axvline(0,color='gray',linestyle='--',linewidth=0.5)

plt.gca().set_aspect('equal')

plt.grid(True,linestyle='--',alpha=0.5)

plt.show()

#source code --> clcoding.com 

Code Explanation:

1. Importing Required Library

import matplotlib.pyplot as plt

matplotlib.pyplot is a widely used Python library for data visualization.

The alias plt is used to simplify function calls.



2. Defining the Diamond Outline Coordinates

diamond_x = [0, 1, 0, -1, 0]

diamond_y = [1, 0, -1, 0, 1]

These two lists store the x and y coordinates of the diamond's outline.

Each coordinate pair represents a point on the diamond.

The sequence of points:

(0,1) → Top

(1,0) → Right

(0,-1) → Bottom

(-1,0) → Left

(0,1) → Closing back to the top


3. Creating the Figure

plt.figure(figsize=(5, 5))

Creates a new figure (canvas) for the plot.

figsize=(5,5) sets the figure size to 5x5 inches, ensuring a square aspect ratio.


4. Plotting the Diamond Outline

plt.plot(diamond_x, diamond_y, 'b-', linewidth=2)

The plot() function draws a line connecting the points.

'b-':

'b' → Blue color for the line.

'-' → Solid line style.

linewidth=2 → Sets the line thickness.


5. Setting Plot Limits

plt.xlim(-1.5, 1.5)

plt.ylim(-1.5, 1.5)

Defines the range of x and y axes.

Ensures the entire diamond fits within the plot with some padding.


6. Adding Reference Lines

plt.axhline(0, color='gray', linestyle='--', linewidth=0.5)

plt.axvline(0, color='gray', linestyle='--', linewidth=0.5)

These lines add dashed reference axes at x = 0 and y = 0.

Helps to center the diamond visually.


7. Ensuring Square Aspect Ratio

plt.gca().set_aspect('equal')

plt.gca() gets the current axes.

.set_aspect('equal') ensures equal scaling on both axes, so the diamond is not distorted.


8. Adding a Grid

plt.grid(True, linestyle='--', alpha=0.5)

Enables a dashed grid to improve visualization.

alpha=0.5 makes the grid slightly transparent.


9. Displaying the Plot

plt.show()

This renders and displays the plot.


Wave pattern plot using python

 


import numpy as np
import matplotlib.pyplot as plt

x=np.linspace(0,10,400)
y1=np.sin(2*np.pi*x)
y2=np.sin(2*np.pi*x+np.pi/2)

plt.figure(figsize=(8,5))
plt.plot(x,y1,label="Wave 1(sin)",color='royalblue',linewidth=2)
plt.plot(x, y2, label="Wave 2 (sin + ฯ€/2)", color="crimson", linestyle="--", linewidth=2)

plt.title("Wave pattern plot",fontsize=14,fontweight="bold")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.grid(True,linestyle='--',alpha=0.6)
plt.show()
#source code --> clcoding.com 

Code Explanation:

Import Required Libraries

import numpy as np

import matplotlib.pyplot as plt

numpy (np) is used for numerical operations and generating data points.

matplotlib.pyplot (plt) is used for visualization.


Generate X-Axis Values

x = np.linspace(0, 10, 400)

np.linspace(0, 10, 400) creates 400 evenly spaced points between 0 and 10.

This ensures a smooth wave curve instead of a jagged one.


Define Two Wave Functions

y1 = np.sin(2 * np.pi * x)       

y2 = np.sin(2 * np.pi * x + np.pi/2)

y1 = sin(2ฯ€x): A standard sine wave.

y2 = sin(2ฯ€x + ฯ€/2): A phase-shifted sine wave (shifted by ฯ€/2).

This means y2 leads y1 by 90 degrees, so the two waves are out of sync.


Create the Figure and Plot the Waves

plt.figure(figsize=(8, 5))

Creates a figure with an 8×5 inch size, ensuring a properly scaled plot.


plt.plot(x, y1, label="Wave 1 (sin)", color="royalblue", linewidth=2)

plt.plot(x, y2, label="Wave 2 (sin + ฯ€/2)", color="crimson", linestyle="--", linewidth=2)

plt.plot(x, y1, ...): Plots the first sine wave (y1) in royal blue.

plt.plot(x, y2, ...): Plots the second sine wave (y2) in crimson with a dashed (--) line style.

linewidth=2: Makes the lines thicker for better visibility.

label="...": Adds labels for the legend.


Customize the Plot

plt.title("Dual Wave Pattern", fontsize=14, fontweight="bold")

Adds a bold title with a font size of 14.

plt.xlabel("X-axis")

plt.ylabel("Y-axis")

Labels the X-axis and Y-axis.

plt.grid(True, linestyle="--", alpha=0.6)

Adds a grid to improve readability.

Dashed grid lines (--) with a slight transparency (alpha=0.6).


plt.legend()

Displays a legend to distinguish the two waves.


Show the Plot

plt.show()

Displays the final sine wave plot.


Arrow pattern plot using python

 


import numpy as np

import matplotlib.pyplot as plt

x,y=np.meshgrid(np.arange(0,10,1),np.arange(0,10,1))

u=np.cos(x)

v=np.sin(y)

plt.figure(figsize=(6,6))

plt.quiver(x,y,u,v,angles='xy',scale_units='xy',scale=2,color='b')

plt.xlim(-1,10)

plt.ylim(-1,10)

plt.title("Arrow pattern plot")

plt.xlabel("X-axis")

plt.ylabel("Y-axis")

plt.grid(True)

plt.show()

#source code --> clcoding.com 

Code Explanation:

Import Necessary Libraries

import numpy as np

import matplotlib.pyplot as plt

numpy is used to generate numerical data efficiently.

matplotlib.pyplot is used for plotting.


Create a Grid of Points

x, y = np.meshgrid(np.arange(0, 10, 1), np.arange(0, 10, 1))

np.meshgrid() generates a grid of (x, y) coordinates in the range 0 to 9.

np.arange(0, 10, 1) creates a sequence from 0 to 9 (step size 1).

This results in a 10×10 grid.


Define Arrow Directions

u = np.cos(x)  

v = np.sin(y)  

u = np.cos(x): The X-component of the arrow is calculated using cos(x), meaning arrow direction in the x-axis varies based on x.

v = np.sin(y): The Y-component of the arrow is calculated using sin(y), meaning arrow direction in the y-axis varies based on y.


Create a Figure & Plot the Arrows

plt.figure(figsize=(6, 6))

plt.quiver(x, y, u, v, angles='xy', scale_units='xy', scale=2, color='b')

plt.figure(figsize=(6,6)): Creates a 6×6-inch figure.

plt.quiver(x, y, u, v, ...):

x, y: Positions of arrows on the grid.

u, v: Arrow directions (vectors).

angles='xy': Ensures arrows follow a Cartesian coordinate system.

scale_units='xy': Ensures correct arrow scaling.

scale=2: Adjusts arrow size.

color='b': Sets the arrow color to blue.


Set Axis Limits & Labels

plt.xlim(-1, 10)

plt.ylim(-1, 10)

Defines the x-axis and y-axis limits from -1 to 10 for better visualization.


plt.title("Arrow Pattern plot")

plt.xlabel("X-axis")

plt.ylabel("Y-axis")

Sets title and axis labels to describe the plot.


plt.grid(True)

Enables grid lines for better readability.


Display the Plot

plt.show()

Displays the generated arrow pattern plot.


Popular Posts

Categories

100 Python Programs for Beginner (118) AI (161) Android (25) AngularJS (1) Api (6) Assembly Language (2) aws (27) Azure (8) BI (10) Books (254) Bootcamp (1) C (78) C# (12) C++ (83) Course (84) Coursera (299) Cybersecurity (28) Data Analysis (24) Data Analytics (16) data management (15) Data Science (226) Data Strucures (14) Deep Learning (76) Django (16) Downloads (3) edx (21) Engineering (15) Euron (30) Events (7) Excel (17) Finance (9) flask (3) flutter (1) FPL (17) Generative AI (49) Git (6) Google (47) Hadoop (3) HTML Quiz (1) HTML&CSS (48) IBM (41) IoT (3) IS (25) Java (99) Leet Code (4) Machine Learning (198) Meta (24) MICHIGAN (5) microsoft (9) Nvidia (8) Pandas (12) PHP (20) Projects (32) Python (1222) Python Coding Challenge (904) Python Quiz (350) Python Tips (5) Questions (2) R (72) React (7) Scripting (3) security (4) Selenium Webdriver (4) Software (19) SQL (45) Udemy (17) UX Research (1) web application (11) Web development (7) web scraping (3)

Followers

Python Coding for Kids ( Free Demo for Everyone)