Python script to create a circle consisting of 7 rainbow-colored pizza slices
This script creates a SVG consisting of 7 equally sized “pizza slices”:
from xml.etree.ElementTree import Element, SubElement, tostring
import math
# Function to generate the SVG
def create_rainbow_pizza_svg(filename):
# Define SVG properties
svg_width = 200
svg_height = 200
radius = 100
cx, cy = svg_width // 2, svg_height // 2
# Colors of the rainbow
rainbow_colors = [
"red", "orange", "yellow", "green", "blue", "indigo", "violet"
]
# Calculate angles for slices
num_slices = len(rainbow_colors)
angle_per_slice = 2 * math.pi / num_slices
# Create SVG root
svg = Element('svg', {
'xmlns': 'http://www.w3.org/2000/svg',
'viewBox': f"0 0 {svg_width} {svg_height}",
'width': str(svg_width),
'height': str(svg_height),
})
for i, color in enumerate(rainbow_colors):
# Calculate start and end angles
start_angle = i * angle_per_slice
end_angle = (i + 1) * angle_per_slice
# Calculate points for the slice
x1 = cx + radius * math.cos(start_angle)
y1 = cy - radius * math.sin(start_angle)
x2 = cx + radius * math.cos(end_angle)
y2 = cy - radius * math.sin(end_angle)
# Create path for the slice
path_data = (
f"M {cx} {cy} " # Move to circle center
f"L {x2:.2f} {y2:.2f} " # Line to first edge of slice
f"A {radius} {radius} 0 0 1 {x1:.2f} {y1:.2f} " # Arc to second edge
f"Z" # Close path
)
path = SubElement(svg, 'path', {
'd': path_data,
'fill': color,
})
# Write to file
with open(filename, "w") as f:
f.write(tostring(svg, encoding='unicode'))
# Create the SVG
create_rainbow_pizza_svg("rainbow_pizza.svg")
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow