Sunday, 23 February 2025

Butterfly pattern plot using python


import numpy as np
import matplotlib.pyplot as plt
t=np.linspace(0,2*np.pi,300)

x = np.sin(t)*(np.exp(np.cos(t))-2*np.cos(4*t))  
y = np.cos(t)*(np.exp(np.cos(t))-2*np.cos(4*t))  

plt.plot(x,y,color='purple',linewidth=2)
plt.plot(-x,y,color='orange',linewidth=2)

plt.title("Beautiful butterfly pattern plot",fontsize=14)
plt.axis("off")
plt.axis("equal")
plt.show()
#source code --> clcoding.com 

Code Explanation:

Importing Necessary Libraries

import numpy as np

import matplotlib.pyplot as plt

numpy: Used to generate an array of numbers (t) and perform mathematical operations.

matplotlib.pyplot: Used to plot the butterfly pattern.

Generating Values for the Plot

t = np.linspace(0, 2*np.pi, 300)

t is a NumPy array containing 300 values evenly spaced between 0 and 2ฯ€.

These values act as the parameter for our equations.


Defining the X and Y Coordinates

x = np.sin(t) * (np.exp(np.cos(t)) - 2*np.cos(4*t))  

y = np.cos(t) * (np.exp(np.cos(t)) - 2*np.cos(4*t))  

np.sin(t) and np.cos(t) create a symmetrical shape.

These equations define a butterfly-like pattern.


Creating the Plot

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

This sets the figure size to 6x6 inches.

It ensures that the butterfly shape is not stretched.


Plotting the Butterfly Wings

plt.plot(x, y, color='purple', linewidth=2)   

plt.plot(-x, y, color='orange', linewidth=2)  

The first plot plt.plot(x, y, ...) creates one wing.

The second plot plt.plot(-x, y, ...) mirrors the first wing.

Colors:

Purple for one side

Orange for the mirrored side


Adding Aesthetics

plt.title("Beautiful Butterfly Pattern ", fontsize=14)

plt.axis("equal")  # Keeps the proportions equal

plt.axis("off")    # Hides the axes for a clean look

Title makes the plot more readable.

Equal aspect ratio prevents stretching or distortion.

Axis removal ensures focus on the butterfly.


Displaying the Plot

plt.show()

This renders the butterfly pattern.


Hourglass pattern plot using python


 

import numpy as np

import matplotlib.pyplot as plt

x = np.linspace(-1, 1, 100)

y_upper = 1 - abs(x)  

y_lower = abs(x) - 1  

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

ax.fill_between(x, y_upper, 1, color="royalblue", alpha=0.7)  

ax.fill_between(x, y_lower, -1, color="tomato", alpha=0.7)  

ax.set_xlim(-1.2, 1.2)

ax.set_ylim(-1.2, 1.2)

ax.set_xticks([])

ax.set_yticks([])

ax.set_frame_on(False)

ax.axhline(0, color="black", linewidth=1.2, linestyle="--") 

plt.title("Hourglass Pattern Plot")

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 (e.g., linspace for smooth curves).
matplotlib.pyplot is used for visualization.

Define X-Coordinates for the Plot
x = np.linspace(-1, 1, 100)
np.linspace(-1, 1, 100): Generates 100 evenly spaced points between -1 and 1.
These x values will be used to define the hourglass shape.

Define Y-Coordinates for Upper and Lower Triangles
y_upper = 1 - abs(x)  
y_lower = abs(x) - 1  
y_upper = 1 - abs(x):
This represents the upper inverted triangle.
As x moves from -1 to 1, the y values decrease from 1 to 0 symmetrically.
y_lower = abs(x) - 1:
This represents the lower triangle.
As x moves from -1 to 1, the y values increase from -1 to 0 symmetrically.
Together, they form an hourglass shape!

Create the Plot
fig, ax = plt.subplots(figsize=(6, 6))
fig, ax = plt.subplots(figsize=(6, 6)):
Creates a square-shaped figure of size 6x6.

Fill the Upper and Lower Triangles
ax.fill_between(x, y_upper, 1, color="royalblue", alpha=0.7)  
ax.fill_between(x, y_lower, -1, color="tomato", alpha=0.7)
fill_between(x, y_upper, 1, color="royalblue", alpha=0.7):
Fills the area between y_upper and 1 with blue.
fill_between(x, y_lower, -1, color="tomato", alpha=0.7):
Fills the area between y_lower and -1 with red.
alpha=0.7:
Transparency of 70% (makes colors blend better).

Adjust Axis Limits and Appearance
ax.set_xlim(-1.2, 1.2)
ax.set_ylim(-1.2, 1.2)
ax.set_xticks([])
ax.set_yticks([])
ax.set_frame_on(False)
ax.set_xlim(-1.2, 1.2): Expands x-axis slightly beyond -1 and 1.
ax.set_ylim(-1.2, 1.2): Expands y-axis slightly beyond -1 and 1.
ax.set_xticks([]): Removes x-axis tick marks.
ax.set_yticks([]): Removes y-axis tick marks.
ax.set_frame_on(False): Removes the border around the plot.

Add a Symmetry Line
ax.axhline(0, color="black", linewidth=1.2, linestyle="--")
axhline(0, color="black", linewidth=1.2, linestyle="--"):
Draws a dashed black line at y = 0 to emphasize symmetry.

Add Title and Display Plot
ax.set_title("Hourglass Pattern Plot", fontsize=14, fontweight="bold")
plt.show()
set_title("Hourglass Pattern Plot", fontsize=14, fontweight="bold"):
Adds a bold title with font size 14.
plt.show():
Displays the final hourglass pattern.

Python Coding challenge - Day 387| What is the output of the following Python Code?

 


Step-by-Step Execution:

1. Import lru_cache from functools
lru_cache (Least Recently Used Cache) is a built-in Python decorator that caches function calls to optimize performance.
It stores previously computed values, avoiding redundant calculations.

2. Define the Fibonacci Function with Caching
@lru_cache(maxsize=2)
def fib(n): 
    return n if n <= 1 else fib(n-1) + fib(n-2)
@lru_cache(maxsize=2): Caches the two most recently used function calls.
Base case: fib(0) = 0, fib(1) = 1
Recursive case: fib(n) = fib(n-1) + fib(n-2)

3. Compute fib(10)
print(fib(10))
The function computes fib(10) using recursion and caches recent calls.
Since maxsize=2, only the last two computed results remain cached.

4. Print Cache Information
print(fib.cache_info())

This outputs:
CacheInfo(hits=X, misses=Y, maxsize=2, currsize=2)
hits: How many times a cached value was used.
misses: How many times a new value was computed.
maxsize: Maximum cache size (2 in this case).
currsize: Current number of cached values (2).

Final Output:

Cache only keeps last 2 calls

Python Coding challenge - Day 386| What is the output of the following Python Code?

 


Step-by-Step Execution:

1. Import weakref Module

The weakref module in Python allows the creation of weak references to objects.

A weak reference does not prevent an object from being garbage collected.

2. Define the Node Class

The Node class has:

__init__: Initializes self.value with the given argument.

__repr__: Defines a string representation for the object (Node(value)).

3. Create a Node Object

node = Node(10)

Creates an instance of Node with value = 10.

node is now a strong reference to the object.

4. Create a Weak Reference

weak_node = weakref.ref(node)

weak_node is a weak reference to node.

This means weak_node does not increase the reference count of node, and it won't prevent garbage collection.

5. Print the Weak Reference

print(weak_node()) 

Calling weak_node() dereferences it, returning the actual Node(10) object if it is still alive.

Since node is still strongly referenced, the output is:

Node(10)


Final Output:

Node(10)


Saturday, 22 February 2025

Sandglass Pattern plot using python

 

import numpy as np

import matplotlib.pyplot as plt

x = np.linspace(-1, 1, 100)

y_upper = 1 - abs(x)  

y_lower = abs(x) - 1  

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

ax.fill_between(x, y_upper, 1, color="royalblue", alpha=0.7)  

ax.fill_between(x, y_lower, -1, color="tomato", alpha=0.7)  

ax.set_xlim(-1.2, 1.2)

ax.set_ylim(-1.2, 1.2)

ax.set_xticks([])

ax.set_yticks([])

ax.set_frame_on(False)

ax.axhline(0, color="black", linewidth=1.2, linestyle="--") 

plt.title("Hourglass Pattern Plot")

plt.show()

#source code --> clcoding.com 


Code Explanation:

Import Necessary Libraries

import numpy as np

import matplotlib.pyplot as plt

numpy is used for numerical operations, such as generating x values.

matplotlib.pyplot is used for visualization.


Define X-Coordinates for the Plot

x = np.linspace(-1, 1, 200)

np.linspace(-1, 1, 200):

Generates 200 evenly spaced values between -1 and 1 for smooth curves.

These values are used for defining the sandglass shape.


Define Y-Coordinates for the Upper and Lower Parts

y_upper = 1 - np.abs(x)  # Top inverted triangle

y_lower = np.abs(x) - 1  # Bottom triangle

y_upper = 1 - np.abs(x):

Defines an inverted triangle (top part of the sandglass).

As x moves from -1 to 1, y_upper decreases from 1 to 0.

y_lower = np.abs(x) - 1:

Defines a regular triangle (bottom part of the sandglass).

As x moves from -1 to 1, y_lower increases from -1 to 0.

Together, they form a symmetrical sandglass shape!


Create the Figure and Set Background

fig, ax = plt.subplots(figsize=(6, 8), facecolor="black")

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

Creates a taller figure (6x8) to emphasize the sandglass shape.

facecolor="black":

Sets the background color to black for better contrast.


Apply a Gradient Effect for Depth

for i in range(8):

    alpha = (8 - i) / 8  # Fading effect

    scale = 1 - i * 0.1  # Shrinking effect for layers

    ax.fill_between(x * scale, y_upper * scale, 1 * scale, color="deepskyblue", alpha=alpha)

    ax.fill_between(x * scale, y_lower * scale, -1 * scale, color="orangered", alpha=alpha)

A loop is used to create multiple layers to simulate a gradient depth effect.

alpha = (8 - i) / 8:

Decreases transparency from 1 to 0.1 as layers go deeper.

scale = 1 - i * 0.1:u

Shrinks each layer slightly to create a depth illusion.

fill_between() is used to fill the upper (blue) and lower (red) triangles.

This creates a smooth, glass-like fading effect, making the sandglass look more 3D.


Add a Dashed Symmetry Line

ax.axhline(0, color="white", linestyle="--", linewidth=1.2, alpha=0.6)

axhline(0): Draws a horizontal dashed line at y = 0.

This emphasizes symmetry and gives a structured appearance.


Remove Axis Details for a Clean Look

ax.set_xlim(-1.2, 1.2)

ax.set_ylim(-1.2, 1.2)

ax.set_xticks([])

ax.set_yticks([])

ax.set_frame_on(False)

set_xlim(-1.2, 1.2) / set_ylim(-1.2, 1.2):

Expands axes slightly for better visibility.

set_xticks([]) / set_yticks([]):

Removes axis labels to make the plot cleaner.

set_frame_on(False):

Removes the frame/border for a sleek look.


Add a Title and Show the Plot

ax.set_title("Sandglass Pattern Plot ", fontsize=14, fontweight="bold", color="white", pad=15)

plt.show()

Adds a bold, centered title with white color.

plt.show(): Displays the final sandglass plot.


Python Coding Challange - Question With Answer(01220225)

 


Code Analysis and Explanation


queue = {'name', 'age', 'DOB'}
print(queue)

1. Understanding the Code

  • queue is assigned a set containing three string elements: 'name', 'age', and 'DOB'.
  • The print(queue) statement displays the contents of the set.

2. Key Properties of Sets in Python

a) Sets are Unordered

  • Unlike lists ([]) or tuples (()), sets {} do not maintain a fixed order for their elements.
  • When printing, Python determines the order dynamically, so the output may vary each time you run the code.

b) Sets Contain Unique Elements

  • If duplicate values were added to the set, Python would automatically remove them because sets store only unique values.

c) Sets are Mutable

  • You can add or remove elements from a set using .add() and .remove().

3. Possible Outputs

Since sets do not maintain order, the printed output could be any of the following:


{'name', 'age', 'DOB'}
{'age', 'DOB', 'name'} {'DOB', 'name', 'age'}
{'DOB', 'age', 'name'}
  • The elements will always be present, but their order is not guaranteed.

4. Why is the Order Different Each Time?

  • Sets are implemented as hash tables in Python.
  • Hashing ensures fast lookups but does not maintain order.

5. What If You Want a Fixed Order?

If you want to maintain order, consider:

  1. Using a List ([])

    queue = ['name', 'age', 'DOB']
    print(queue) # Always prints: ['name', 'age', 'DOB']
  2. Sorting the Set Before Printing


    print(sorted(queue)) # Prints: ['DOB', 'age', 'name']

6. Example Set Operations


queue.add('gender') # Add an element
queue.remove('age') # Remove an element
print(queue) # Output may vary

7. Summary

Sets are unordered → Elements may print in a different order.
Sets contain unique elements → Duplicates are automatically removed.
Use lists if order matters → Lists maintain insertion order.

Python Coding challenge - Day 385 What is the output of the following Python Code?

 


Explanation:

1. Understanding partial from functools

The partial function is used to fix some arguments of a function, creating a new function with fewer parameters.

2. Defining the Function add

def add(x, y, z):

    return x + y + z

This function takes three parameters (x, y, and z) and returns their sum.

3. Using partial to Create add_five

add_five = partial(add, 5)

Here, partial(add, 5) creates a new function add_five where the first argument (x) is pre-filled with 5.

add_five(y, z) is now equivalent to calling add(5, y, z).

4. Calling add_five(3, 2)

print(add_five(3, 2))

Since add_five is partial(add, 5), calling add_five(3, 2) is the same as calling:

add(5, 3, 2)

5 + 3 + 2 = 10, so the output is:


Output:

10

Python Coding challenge - Day 384| What is the output of the following Python Code?

 


Explanation:

Class A Definition:

A is a class that has a method show() which returns the string "A".

Class B Definition:

B is a subclass of A (class B(A):), meaning B inherits everything from A.

The keyword pass is used, which means B does not introduce any new attributes or methods—it simply inherits from A.

Creating an Instance of B:

B() creates an object of class B.

Calling show() on an Instance of B:

print(B().show()):

Since B does not have its own show() method, it looks up the method in its parent class (A).

The show() method of A is executed, returning "A".

Output:

A

Friday, 21 February 2025

Spiral Pattern plot using python



 import matplotlib.pyplot as plt

import numpy as np

theta=np.linspace(0,4*np.pi,500)

r=np.linspace(0,10,500)

x=r*np.cos(theta)

y=r*np.sin(theta)

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

plt.plot(x,y,color='blue',linewidth=2)

plt.title("Spiral pattern plot")

plt.axis("equal")

plt.show()

#source code --> clcoding.com

Code Explanation:

1. Import Necessary Libraries

import numpy as np

import matplotlib.pyplot as plt

numpy is used for numerical operations, like creating arrays.

matplotlib.pyplot is used for plotting graphs.


2. Define the Spiral Parameters

theta = np.linspace(0, 4 * np.pi, 500)  # Angle values

r = np.linspace(0, 10, 500)  # Radius values

theta represents the angle in radians, ranging from 0 to 4ฯ€ (two full turns).

r represents the radius, increasing from 0 to 10.

np.linspace(start, stop, num_points) creates 500 evenly spaced values.


3. Convert to Cartesian Coordinates

x = r * np.cos(theta)

y = r * np.sin(theta)

The spiral is defined in polar coordinates (r, ฮธ), but Matplotlib uses Cartesian coordinates (x, y).


4. Plot the Spiral

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

plt.plot(x, y, color='blue', linewidth=2)

plt.title("Spiral Pattern")

plt.axis("equal")  # Keep aspect ratio equal

plt.show()

plt.figure(figsize=(6,6)): Creates a square figure (6x6 inches).

plt.plot(x, y, color='blue', linewidth=2): Plots the spiral in blue with a thicker line.

plt.title("Spiral Pattern"): Adds a title to the plot.

plt.axis("equal"): Ensures equal scaling on both axes to maintain the circular shape.

plt.show(): Displays the plot.


Zig Zag pattern plot using python

 


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.

X Shaped pattern plot using python

 


import matplotlib.pyplot as plt

size=10

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

for i in range(size):

    plt.plot([i,size-1-i],[i,i],'bo')

    plt.plot([i,size-1-i],[size-1-i,size-1-i],'bo')


ax.set_xlim(-1,size)

ax.set_ylim(-1,size)

ax.set_xticks([])

ax.set_yticks([])

ax.set_frame_on(False)

plt.title('X shaped pattern')

plt.show()

#source code --> clcoding.com 

Code Explanation:

1. Import Required Libraries
import numpy as np
import matplotlib.pyplot as plt
numpy is imported but not used in the code. It is typically helpful for numerical computations.
matplotlib.pyplot is used to create the plot.

2. Define Grid Size
size = 10  # Change this for a larger or smaller X shape
This variable size determines how large the "X" shape will be.
It represents the number of rows and columns in the pattern.

3. Create Figure and Axis
fig, ax = plt.subplots(figsize=(6, 6))
plt.subplots() creates a figure (fig) and an axis (ax).
figsize=(6,6) sets the size of the figure to 6 inches by 6 inches.

4. Generate X-Shaped Pattern
for i in range(size):
    plt.plot([i, size - 1 - i], [i, i], 'bo')  # Top-left to bottom-right
    plt.plot([i, size - 1 - i], [size - 1 - i, size - 1 - i], 'bo')  # Bottom-left to top-right
This loop iterates from 0 to size-1.
The first plt.plot():
Plots points along the diagonal from top-left to bottom-right (\).
(i, i) and (size - 1 - i, i) define the start and end points of a line.
The second plt.plot():
Plots points along the diagonal from bottom-left to top-right (/).
(i, size - 1 - i) and (size - 1 - i, size - 1 - i) define the points.

5. Set Axis Limits
ax.set_xlim(-1, size)
ax.set_ylim(-1, size)
Ensures that the plotted points fit well within the graph area.
Limits are slightly beyond the grid (-1 to size) to provide padding.

6. Remove Axes for a Cleaner Look
ax.set_xticks([])
ax.set_yticks([])
ax.set_frame_on(False)
ax.set_xticks([]) and ax.set_yticks([]) remove the tick marks.
ax.set_frame_on(False) removes the surrounding box.

7. Display the Plot
plt.show()
This command displays the generated X-shaped pattern.


Plus(+)pattern plot using python


 import matplotlib.pyplot as plt


x_horiz=[-1,1]

y_horiz=[0,0]

x_vert=[0,0]

y_vert=[-1,1]

plt.plot(x_horiz,y_horiz,'b-',linewidth=3)

plt.plot(x_vert,y_vert,'b-',linewidth=3)

plt.xlim(-2,2)

plt.ylim(-2,2)

plt.grid(True)

plt.title('Plus pattern plot')

plt.show()

#source code --> clcoding.com 

Code Explanation:

1. Importing Matplotlib
import matplotlib.pyplot as plt
This imports matplotlib.pyplot, which is used for plotting in Python.

2. Defining Coordinates for the Plus (+) Shape
x_horiz = [-1, 1]  
y_horiz = [0, 0]  
This represents the horizontal line of the plus sign.
The line extends from x = -1 to x = 1, while keeping y = 0.
x_vert = [0, 0]    
y_vert = [-1, 1]   
This represents the vertical line of the plus sign.
The line extends from y = -1 to y = 1, while keeping x = 0.

3. Plotting the Horizontal and Vertical Lines
plt.plot(x_horiz, y_horiz, 'b-', linewidth=3)  
plt.plot(x_vert, y_vert, 'b-', linewidth=3)    
plt.plot(x_horiz, y_horiz, 'b-', linewidth=3)
Plots the horizontal line in blue (b).
Uses a solid line (-).
linewidth=3 makes the line thicker.
plt.plot(x_vert, y_vert, 'b-', linewidth=3)
Plots the vertical line using the same style.
Together, these lines form a plus (+) sign.

4. Setting Axis Limits
plt.xlim(-2, 2)  
plt.ylim(-2, 2)  
plt.xlim(-2, 2) sets the x-axis limits from -2 to 2.
plt.ylim(-2, 2) sets the y-axis limits from -2 to 2.
This ensures the plus sign is centered and visible.

5. Enabling Grid
plt.grid(True)
Adds a grid to the plot for better visualization.

6. Adding a Title
plt.title("Plus Pattern Plot")
Adds a title to the plot.

7. Displaying the Plot
plt.show()
This function renders and displays the plot.

Cross pattern plot


 import matplotlib.pyplot as plt

x=[0,0,-1,1,0,0]

y=[-1,1,0,0,-2,2]


plt.scatter(x,y,color='red')

plt.axhline(0,color='black',linewidth=0.5)

plt.axvline(0,color='black',linewidth=0.5)


plt.xlim(-2,2)

plt.ylim(-2,2)

plt.grid(True)


plt.title('Cross pattern plot')

plt.show()

#source code --> clcoding.com 

Code Explanation:

1. Importing Matplotlib
import matplotlib.pyplot as plt
This imports matplotlib.pyplot, which is a library used for creating plots in Python.

2. Defining Coordinates for the Cross
x = [0, 0, -1, 1, 0, 0]  # X-coordinates
y = [-1, 1, 0, 0, -2, 2]  # Y-coordinates
The x and y lists define the positions of points that form a cross shape.
The points are:
(0, -1)
(0, 1)
(-1, 0)
(1, 0)
(0, -2)
(0, 2)
These points create a cross pattern, where (0, 0) is the center.

3. Plotting the Points Using scatter
plt.scatter(x, y, color='red')
This function plots individual points at the given (x, y) coordinates.
The points are displayed as red dots.

4. Drawing Reference Lines
plt.axhline(0, color='black', linewidth=0.5)  # Draws a horizontal line at y=0
plt.axvline(0, color='black', linewidth=0.5)  # Draws a vertical line at x=0
These lines enhance visibility of the cross pattern:
plt.axhline(0): Draws a black horizontal line at y = 0.
plt.axvline(0): Draws a black vertical line at x = 0.
This helps center the cross visually.

5. Setting Plot Limits
plt.xlim(-2, 2)  # Limits the x-axis from -2 to 2
plt.ylim(-2, 2)  # Limits the y-axis from -2 to 2
This ensures that the cross is fully visible within a square frame.

6. Enabling Grid
plt.grid(True)
Adds a grid to the plot for better visualization.

7. Adding a Title
plt.title("Cross Pattern Plot")
This sets the title of the plot.

8. Displaying the Plot
plt.show()
Finally, plt.show() displays the plot.


Checkboard pattern plot using python

 


import numpy as np
import matplotlib.pyplot as plt

def plot_checkboard(size=8):
    board=np.indices((size,size)).sum(axis=0)%2
    
    plt.figure(figsize=(6,6))
    plt.imshow(board,cmap="gray",interpolation="nearest")
    
    plt.xticks([])
    plt.yticks([])
    plt.title('checkboard pattern plot')
    plt.show()
plot_checkboard(8)   

#source code --> clcoding.com 

Code Explanation:

Importing Required Libraries
import numpy as np
import matplotlib.pyplot as plt
numpy is used to generate the checkerboard pattern as a 2D array.
matplotlib.pyplot is used to plot the pattern.

Function Definition
def plot_checkerboard(size=8):
This function creates and plots a checkerboard of size × size squares.
The default board size is 8 × 8, like a chessboard.

Creating the Checkerboard Pattern
board = np.indices((size, size)).sum(axis=0) % 2
How This Works:
np.indices((size, size)) creates two 2D arrays of indices:
row_indices, col_indices = np.indices((8, 8))
Applying % 2:
If (row + col) % 2 == 0, it’s black (0).
If (row + col) % 2 == 1, it’s white (1).
Final Checkerboard (8×8) Array:
[[0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]
 [0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]
 [0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]
 [0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]]
This alternating 0s and 1s forms a checkerboard pattern.

Plotting the Checkerboard
plt.figure(figsize=(6, 6))
plt.imshow(board, cmap="gray", interpolation="nearest")
plt.figure(figsize=(6,6)) → Sets the figure size.
plt.imshow(board, cmap="gray", interpolation="nearest")
board: The checkerboard array.
cmap="gray": Uses grayscale colors (0 = black, 1 = white).
interpolation="nearest": Ensures sharp edges between squares.

Formatting for a Clean Look
plt.xticks([])
plt.yticks([])
plt.title("Checkerboard Pattern", fontsize=14, fontweight='bold')
plt.xticks([]), plt.yticks([]): Removes axis labels for a clean look.
plt.title(...): Adds a title to the plot.

Displaying the Plot
plt.show()
Displays the checkerboard plot.
When calling:
plot_checkerboard(8)
You get a black and white checkerboard with an 8×8 grid.

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)