Skip to content

American Flag

This Python program utilizes Matplotlib, a powerful plotting library, to visually render the flag of the United States of America. The flag, known for its distinctive red, white, and blue stripes and stars, is meticulously constructed using geometric shapes and precise coordinates. Let’s explore how this program generates the iconic American flag step by step.

1. Initial Settings

The program begins by importing necessary libraries and configuring the plotting environment to ensure high-resolution output. Key colors of the American flag are defined using RGB values to accurately represent the red, white, and blue elements.

2. Drawing Stripes

The program constructs the 13 alternating red and white stripes that symbolize the original colonies of the United States.

3. Drawing the Blue Box

A blue rectangle is drawn in the top left corner of the flag to represent the union of the states, adorned with stars.

4. Placing stars

Using calculated coordinates, the program places 50 white stars in the blue field, representing the 50 states of the United States.

5. Final Adjustments and Display

The program concludes by setting plot limits, hiding axis labels, and displaying the completed flag.

import matplotlib.pyplot as plt
import matplotlib.patches as patches
import numpy as np

# Set figure size and resolution settings
plt.rcParams['savefig.dpi']=500
plt.rcParams['figure.dpi']=500
fig, ax = plt.subplots(figsize=(12, 6.6))

# Define the three flag colors
RED = (178/255, 34/255, 52/255)
WHITE = (255/255, 255/255, 255/255)
BLUE = (60/255, 59/255, 110/255)

# Draw stripes
for i in range(13):
    color = RED if i % 2 == 0 else WHITE
    ax.add_patch(patches.Rectangle((0, i/13), 1.9, 1/13, color=color))
    
# Draw blue box for stars
ax.add_patch(patches.Rectangle((0, 6/13), 0.76, 7/13, color=BLUE))

# Star spacing constants
H_SPACING = 0.4 / 6
V_SPACING = 6/13 / 5

# Establish the coordinates for positioning the stars
A=np.arange(0.0633,0.76,0.76/12)
B=np.arange(0.0538+6/13,1,0.0538)
C=np.arange(0,12,2)
D=np.arange(0,10,2)

# Draw stars
for i in C:
    for j in D:
        ax.scatter(A[i],B[j],color='white',marker='*', s=150)
        
for i in C[0:-1]:
    for j in D[0:-1]:
        ax.scatter(A[i+1],B[j+1],color='white',marker='*', s=150)
        
# Cut the margin
ax.set_xlim(0, 1.9)
ax.set_ylim(0, 1)
ax.axis('off')
plt.show()