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.


Thursday, 27 February 2025

Write a program to append the text "This is an additional line." to an existing file.

 


with open("output.txt", "a") as file:

    file.write("This is an additional line.\n")


print("Text appended successfully!")

#source code --> clcoding.com  


Code Explanation:

Open the File in Append Mode ("a")
The open("output.txt", "a") statement opens the file in append mode.
If the file does not exist, Python creates it automatically.
If the file already exists, new content is added at the end without deleting existing data.

Append a New Line to the File
file.write("This is an additional line.\n") adds a new line at the end of the file.
The "\n" ensures the text appears on a new line instead of continuing on the same line.

Automatic File Closure
Using with open(...) ensures the file closes automatically after writing.

Print Success Message

print("Text appended successfully!") confirms that the operation was successful.


Read a file line by line and print each line separately.

 


with open("example.txt", "r") as file:

    for line in file:

        print(line.strip())  

#source code --> clcoding.com         


Code Explanation:

Open the File in Read Mode ("r")
open("example.txt", "r") opens the file in read mode.
If the file does not exist, Python will raise a FileNotFoundError.

Read the File Line by Line
for line in file: iterates through each line in the file.

Print Each Line Separately
print(line.strip()) prints the line after using .strip(), which removes extra spaces or newline characters (\n) from the output.

Create a program that writes a list of strings to a file, each on a new line.

 


lines = ["Hello, World!", "Python is great!", "File handling is useful!", "End of file."]


with open("output.txt", "w") as file:

    for line in lines:

        file.write(line + "\n")


print("Data written to output.txt successfully!")

#source code --> clcoding.com  


Code Explanation:

 Create a List of Strings:
We define a list lines that contains multiple strings.

Open the File in Write Mode ("w")
The open("output.txt", "w") statement opens the file in write mode.
If the file does not exist, it will be created.
If the file already exists, it will be overwritten.

Writing to the File:
The for loop iterates through the list of strings.
file.write(line + "\n") writes each string to the file and adds a newline (\n) so that each string appears on a new line.

File Closes Automatically:
The with open(...) statement ensures the file automatically closes after writing.

Print Success Message:
print("Data written to output.txt successfully!") confirms that the process is complete.

Write a program to read the contents of a file and display them on the screen.

 


with open("example.txt", "r") as file:

    content = file.read()


print("File Contents:")

print(content)

#source code --> clcoding.com  


Code explanation:

Opening the File:
We use open("example.txt", "r") to open the file in read mode ("r").
The "r" mode ensures that we are only reading the file, not modifying it.
If the file does not exist, Python will raise a FileNotFoundError.

Using with Statement:
The with open(...) as file: statement ensures the file is closed automatically after the block is executed.

Reading the File:
The read() function reads all the content from the file and stores it in the variable content.

Printing the Contents:
print(content) displays the contents of the file on the screen.


Write a Python program to create a text file named example.txt and write the text "Hello, World!" into it.

 


with open("example.txt", "w") as file:

    file.write("Hello, World!")


print("File created and text written successfully!")

#source code --> clcoding.com  


Code Explanation:

Opening the File:
We use open("example.txt", "w") to open a file named example.txt in write mode ("w").
If the file does not exist, Python creates it automatically.
If the file already exists, its contents will be overwritten.

Using with Statement:
with open(...) as file: is used for better file handling.
It ensures that the file is closed automatically after the block is executed.

Writing to the File:
The write() function writes "Hello, World!" into the file.

Print Confirmation:
The message "File created and text written successfully!" confirms the operation.

Expected Output:
File created and text written successfully!

Write a program to remove duplicates from a list using a set.

 


numbers = [1, 2, 2, 3, 4, 4, 5, 6, 6, 7, 8, 8, 9]

unique_numbers = list(set(numbers))

print("List without duplicates:", unique_numbers)

#source code --> clcoding.com  


Code Explanation:

Define a List with Duplicates
numbers = [1, 2, 2, 3, 4, 4, 5, 6, 6, 7, 8, 8, 9]
This list contains duplicate values like 2, 4, 6, 8.

Convert the List to a Set
unique_numbers = list(set(numbers))
Sets in Python do not allow duplicate values.
Converting the list to a set automatically removes all duplicates.
Converting it back to a list gives us a duplicate-free list.

Print the Unique List
print("List without duplicates:", unique_numbers)
The final list will have only unique values.

Expected Output
List without duplicates: [1, 2, 3, 4, 5, 6, 7, 8, 9]

Write a program to print all keys and values of a dictionary using a loop


 

student = {"name": "John", "age": 20, "grade": "A"}


for key, value in student.items():

    print(f"Key: {key}, Value: {value}")

#source code --> clcoding.com  


Code Explanation:

Define the Dictionary
student = {"name": "John", "age": 20, "grade": "A"}
We create a dictionary named student that contains:

"name" → "John"
"age" → 20
"grade" → "A"

Use a Loop to Iterate Through the Dictionary
for key, value in student.items():
.items() → This method returns pairs of keys and values from the dictionary.
The for loop assigns each key to key and each value to value on every iteration.

Print the Key-Value Pairs
print(f"Key: {key}, Value: {value}")
We use an f-string (f"...") to format and display the key and value.

Expected Output
Key: name, Value: John
Key: age, Value: 20
Key: grade, Value: A

Popular Posts

Categories

100 Python Programs for Beginner (118) AI (163) 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 (228) Data Strucures (14) Deep Learning (78) 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 (200) Meta (24) MICHIGAN (5) microsoft (9) Nvidia (8) Pandas (12) PHP (20) Projects (32) Python (1224) Python Coding Challenge (907) Python Quiz (352) 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)