Experiment -1
Q. 1 Write a program for drawing graphics primitives and color it .
import matplotlib.pyplot as plt
import matplotlib.patches as p
fig, ax = plt.subplots(figsize=(6, 4))
fig.canvas.manager.set_window_title('Graphic Primitives')
ax.set_xlim(0, 600); ax.set_ylim(0, 400)
ax.invert_yaxis() # (0,0) at top-left like a GUI
# red line
ax.plot([50, 550], [50, 50], color='red', linewidth=2)
# green filled rectangle
ax.add_patch(p.Rectangle((100, 100), 150, 80, facecolor='green', edgecolor='green'))
# blue filled circle
ax.add_patch(p.Circle((350, 250), 50, facecolor='blue', edgecolor='blue'))
# yellow filled ellipse
ax.add_patch(p.Ellipse((450, 350), 120, 80, facecolor='yellow' , edgecolor='yellow'))
ax.set_aspect('equal'); ax.axis('off')
plt.tight_layout(); plt.show()
Output-
Experiment -2
Q. 2 Write a program to divide screen into four region and draw circle, rectangle,
arc and ellipse.
import matplotlib.pyplot as plt
import matplotlib.patches as patches
fig, ax = plt.subplots(figsize=(8, 6))
fig.canvas.manager.set_window_title('Screen Divided Into Four Regions') # Window title
# Set limits for the full screen
ax.set_xlim(0, 800)
ax.set_ylim(0, 600)
ax.invert_yaxis() # Origin (0,0) at top-left like GUI
# Draw dividing lines to create 4 regions
ax.plot([400, 400], [0, 600], color='black', linewidth=1) # vertical center line
ax.plot([0, 800], [300, 300], color='black', linewidth=1) # horizontal center line
# Region 1: Top-left - Circle
circle_center = (200, 150)
circle_radius = 80
circle = patches.Circle(circle_center, circle_radius, facecolor='blue', edgecolor='black')
ax.add_patch(circle)
# Region 2: Top-right - Rectangle
rect_xy = (450, 80) # bottom-left corner of rectangle
rect_width = 200
rect_height = 140
rectangle = patches.Rectangle(rect_xy, rect_width, rect_height, facecolor='green', edgecolor='black')
ax.add_patch(rectangle)
# Region 3: Bottom-left - Filled Wedge (colored arc sector)
arc_center = (200, 450)
arc_radius = 75 # half of width/height used before for arc
wedge = patches.Wedge(arc_center, arc_radius, theta1=0, theta2=90, facecolor='red',
edgecolor='black', linewidth=2)
ax.add_patch(wedge)
# Region 4: Bottom-right - Ellipse
ellipse_center = (600, 450)
ellipse_width = 220
ellipse_height = 120
ellipse = patches.Ellipse(ellipse_center, ellipse_width, ellipse_height, facecolor='orange',
edgecolor='black')
ax.add_patch(ellipse)
ax.set_aspect('equal')
ax.axis('off')
plt.tight_layout()
plt.show()
Output-
Experiment -3
Q. 3 Write a program for drawing a simple object.
import matplotlib.pyplot as plt
x_val = [0, 0, 2, 2, 0]
y_val = [0, 2, 2, 0, 0]
# Fill the square with pink color
plt.fill(x_val, y_val, color='pink', label="Square")
# Also plot the outline with markers
plt.plot(x_val, y_val, marker='o', color='black')
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.title("Square plot")
plt.legend()
plt.axis("equal")
plt.show()
Experiment -4
Q4.Write a program to draw a rectangle. The four vertices of it should be entered
by the end user.
import matplotlib.pyplot as plt
# ---- collect 4 vertices from the user (console prompts) ----
x_pts, y_pts = [], []
for i in range(1, 5):
x = float(input(f"Enter x{i}: "))
y = float(input(f"Enter y{i}: "))
x_pts.append(x)
y_pts.append(y)
# close the rectangle by repeating the first vertex
x_pts.append(x_pts[0])
y_pts.append(y_pts[0])
# ---- draw ----
plt.fill(x_pts, y_pts, color='skyblue', alpha=0.6) # interior
plt.plot(x_pts, y_pts, 'ko-') # outline with dots
plt.gca().set_aspect('equal')
plt.title("Rectangle from User Input")
plt.show()
Output-
Experiment -5
Q5.Write a program for drawing a line using DDA Line Drawing Algorithm.
import matplotlib.pyplot as plt
x1, y1 = map(float, input("x1 y1: ").split())
x2, y2 = map(float, input("x2 y2: ").split())
plt.plot([x1, x2], [y1, y2], 'k-') # draw black line
plt.title("DDA Line Drawing Algorithm")
plt.gca().set_aspect('equal')
plt.show()
Output-
Experiment – 6
Q6. Write a program for drawing a line using Bresahnams Line Drawing Algorithm.
import matplotlib.pyplot as plt
def bresenham(x1, y1, x2, y2):
pts = []
dx, dy = abs(x2 - x1), abs(y2 - y1)
sx = 1 if x2 >= x1 else -1
sy = 1 if y2 >= y1 else -1
err = dx - dy
x, y = x1, y1
while True:
pts.append((x, y))
if x == x2 and y == y2: break
e2 = 2 * err
if e2 > -dy: err -= dy; x += sx
if e2 < dx: err += dx; y += sy
return pts
x1, y1 = map(int, input("x1 y1: ").split())
x2, y2 = map(int, input("x2 y2: ").split())
pix = bresenham(x1, y1, x2, y2)
xp, yp = zip(*pix)
# draw Bresenham pixels
plt.scatter(xp, yp, s=60, marker='s', color='royalblue', label="Bresenham pixels")
# draw the ideal mathematical line for reference
plt.plot([x1, x2], [y1, y2], 'k--', alpha=0.4, label="Ideal line")
plt.gca().set_aspect('equal')
plt.xticks(range(min(xp)-1, max(xp)+2))
plt.yticks(range(min(yp)-1, max(yp)+2))
plt.grid(True, linestyle=':', linewidth=0.4)
plt.legend()
plt.title("Bresenham's Line Drawing (pixels + ideal)")
plt.show()
Output -
Experiment – 7
Q7.Write a program to draw two concentric circles using mid-point circle drawing
algorithm.
import matplotlib.pyplot as plt
def midpoint_circle(cx, cy, r):
"""Return the (x, y) pixels of a circle centered at (cx, cy) with radius r."""
x, y = 0, r
d =1-r # initial decision parameter
points = []
# eight-way symmetry helper
def add_octants(px, py):
points.extend([
( cx + px, cy + py),
( cx - px, cy + py),
( cx + px, cy - py),
( cx - px, cy - py),
( cx + py, cy + px),
( cx - py, cy + px),
( cx + py, cy - px),
( cx - py, cy - px),
])
while x <= y:
add_octants(x, y)
if d < 0: # choose East pixel
d += 2 * x + 3
else: # choose South-East pixel
d += 2 * (x - y) + 5
y -= 1
x += 1
return points
# ---- centre & radii ----
cx, cy = 0, 0 # both circles share this centre
r1 = 20 # inner radius
r2 = 45 # outer radius (concentric)
# ---- get pixels ----
inner = midpoint_circle(cx, cy, r1)
outer = midpoint_circle(cx, cy, r2)
# ---- plot ----
ix, iy = zip(*inner)
ox, oy = zip(*outer)
plt.scatter(ix, iy, s=5, color='blue', marker='s', label=f"r = {r1}")
plt.scatter(ox, oy, s=5, color='crimson', marker='s', label=f"r = {r2}")
plt.gca().set_aspect('equal')
plt.title("Mid-Point Circle Drawing – Two Concentric Circles")
plt.legend()
plt.grid(True, linestyle=':', linewidth=0.1)
plt.show()
Output –
Experiment – 8
Q8. Write a program to draw any 2D object and perform the basic
transformations on it.
import matplotlib.pyplot as plt
import math
# Original triangle
pts = [[0, 0], [4, 0], [2, 3]]
# Get transformation choice
op = input("1=Translate 2=Scale 3=Rotate: ")
# Apply transformation
if op == '1':
tx, ty = map(float, input("tx ty: ").split())
new_pts = [[x+tx, y+ty] for x, y in pts]
elif op == '2':
sx, sy = map(float, input("sx sy: ").split())
new_pts = [[x*sx, y*sy] for x, y in pts]
elif op == '3':
angle = math.radians(float(input("angle: ")))
new_pts = [[x*math.cos(angle)-y*math.sin(angle),
x*math.sin(angle)+y*math.cos(angle)] for x, y in pts]
else:
exit()
# Draw both
def draw(p, label):
p += [p[0]] # close shape
x, y = zip(*p)
plt.plot(x, y, marker='o', label=label)
draw(pts[:], "Original")
draw(new_pts[:], "Transformed")
plt.legend()
plt.axis('equal')
plt.grid()
plt.show()
Output -
Experiment – 9
Q9.Write a program to draw a house like and perform the following operations.
a.Scaling about the origin followed by translation.
b.Scaling with reference to an arbitrary point.
import matplotlib.pyplot as plt
import matplotlib.patches as patches
# Create figure and axis
fig, ax = plt.subplots()
ax.set_aspect('equal')
ax.set_xlim(0, 10)
ax.set_ylim(0, 10)
plt.axis('off') # Turn off axes
# House body
house_body = patches.Rectangle((3, 3), 4, 4, facecolor='lightgrey', edgecolor='lightgrey')
ax.add_patch(house_body)
# Roof
roof = patches.Polygon([[2.5, 7], [5, 9], [7.5, 7]], closed=True, facecolor='dimgray',
edgecolor='dimgray')
ax.add_patch(roof)
# Door
door = patches.Rectangle((4.25, 3), 1.5, 2.5, facecolor='saddlebrown', edgecolor='saddlebrown')
ax.add_patch(door)
# Show the figure
plt.title('Simple House')
plt.show()
Output -
Experiment – 10
Q10. Write a program to draw any 2-D object and perform the transformations on
it according to the input parameters from the user, namely: Shearing and
Reflection.
import matplotlib.pyplot as plt
# Draw polygon
def draw_polygon(points, title="Shape"):
pts = points + [points[0]] # close polygon
x = [p[0] for p in pts]
y = [p[1] for p in pts]
plt.plot(x, y, marker='o')
plt.title(title)
plt.grid(True)
plt.gca().set_aspect('equal', adjustable='box')
# Shearing transformation (manual matrix multiply)
def shear(points, shx=0, shy=0):
result = []
for x, y in points:
new_x = x + shx * y
new_y = shy * x + y
result.append([new_x, new_y])
return result
# Reflection transformation
def reflect(points, axis):
result = []
for x, y in points:
if axis == 'x':
result.append([x, -y])
elif axis == 'y':
result.append([-x, y])
elif axis == 'origin':
result.append([-x, -y])
elif axis == 'y=x':
result.append([y, x])
else:
raise ValueError("Invalid axis for reflection")
return result
# --- Main program ---
print("Enter coordinates of a polygon (e.g., triangle):")
n = int(input("Number of vertices: "))
original_points = []
for i in range(n):
x, y = map(float, input(f"Enter x y for vertex {i+1}: ").split())
original_points.append([x, y])
print("\nChoose Transformation:")
print("1. Shearing")
print("2. Reflection")
choice = input("Enter choice (1 or 2): ")
if choice == '1':
shx = float(input("Enter shearing factor in x-direction (shx): "))
shy = float(input("Enter shearing factor in y-direction (shy): "))
transformed = shear(original_points, shx, shy)
title = "Sheared Shape"
elif choice == '2':
print("Reflection options: x, y, origin, y=x")
axis = input("Enter axis to reflect about: ").lower()
transformed = reflect(original_points, axis)
title = f"Reflected Shape about {axis}"
else:
print("Invalid choice.")
exit()
# Plotting
plt.figure(figsize=(8, 8))
plt.subplot(1, 2, 1)
draw_polygon(original_points, "Original Shape")
plt.subplot(1, 2, 2)
draw_polygon(transformed, title)
plt.show()
Output -