Contents

svgwrite code examples

0

These python code examples will show you how to use the svgwrite module to generate svg images.

The svgwrite documentation is lacking in code examples, this page provides 20 svgwrite code examples demonstrating how to use various aspects of the svgwrite package in your python code.

Basics of SVG Write

This first combined example demostrates many drawing methods of the svgwrite library such as svgwrite.rect, svgwrite.circle, svgwrite.line, svgwrite.text, svgwrite.gradients.LinearGradient and svgwrite.path

Source Code

import svgwrite

dwg = svgwrite.Drawing('svgwrite-example.svg', profile='tiny')

# draw a red box
dwg.add(dwg.rect((10, 10), (300, 200),
    stroke=svgwrite.rgb(10, 10, 16, '%'),
    fill='red')
)

# Draw a small white circle in the top left of box
dwg.add(dwg.circle(center=(25,25),
    r=10,
    stroke=svgwrite.rgb(15, 15, 15, '%'),
    fill='white')
)

# Label this box #1
dwg.add(dwg.text('1',
    insert=(21,30),
    stroke='none',
    fill=svgwrite.rgb(15, 15, 15, '%'),
    font_size='15px',
    font_weight="bold")
)

# Draw some text demonstrating font_size, font_family, font_weight, font_color
dwg.add(dwg.text('ABC',
    insert=(55,125),
    stroke='none',
    fill='#900',
    font_size='90px',
    font_weight="bold",
    font_family="Arial")
)

# Draw some text demonstrating font stroke color
dwg.add(dwg.text('12345',
    insert=(50,180),
    stroke='#500',
    fill='#A90690',
    stroke_width=2,
    font_size='66px',
    font_weight="bold",
    font_family="Courier New")
)

# white text over red box
dwg.add(dwg.text('rectangle w/ black stroke & red fill',
    insert=(40, 40),
    fill='white')
)

# draw a nofill box
dwg.add(dwg.rect((10, 220), (300, 190),
    stroke=svgwrite.rgb(10, 10, 16, '%'),
    fill='none')
)

# black text over nofill box
dwg.add(dwg.text('rectangle w/ black stroke & no fill',
    insert=(40, 250),
    fill='black')
)

# Draw a small white circle in the top left of box
dwg.add(dwg.circle(center=(26,235),
    r=10,
    stroke=svgwrite.rgb(15, 15, 15, '%'),
    fill='#eeeeee')
)

# Label this box #2
dwg.add(dwg.text('2',
    insert=(22,240),
    stroke='none',
    fill=svgwrite.rgb(15, 15, 15, '%'),
    font_size='15px',
    font_weight="bold")
)

# Create a vertical linear gradient and add it the svg's definitions
vert_grad = svgwrite.gradients.LinearGradient(start=(0, 0), end=(0,1), id="vert_lin_grad")
vert_grad.add_stop_color(offset='0%', color='blue', opacity=None)
vert_grad.add_stop_color(offset='50%', color='green', opacity=None)
vert_grad.add_stop_color(offset='100%', color='yellow', opacity=None)
dwg.defs.add(vert_grad)

# draw a box and reference the above gradient definition by #id
dwg.add(dwg.rect((35, 270), (240, 120),
    stroke=svgwrite.rgb(10, 10, 16, '%'),
    fill="url(#vert_lin_grad)"
))

# black text over nofill box
dwg.add(dwg.text('rectangle w/ linear gradient',
    insert=(60, 330),
    fill='white')
)

# draw a blue box
dwg.add(dwg.rect((320,10), (400, 400),
    stroke=svgwrite.rgb(10, 10, 16, '%'),
    fill='blue')
)

# yellow text over blue box
dwg.add(dwg.text('rectangle w/ black stroke & blue fill',
    insert=(360, 40),
    fill='yellow')
)

# Draw a small white circle in the top left of box
dwg.add(dwg.circle(center=(335,25),
    r=10,
    stroke=svgwrite.rgb(15, 15, 15, '%'),
    fill='#eeeeee')
)

# Label this box #3
dwg.add(dwg.text('3',
    insert=(331,30),
    stroke='none',
    fill=svgwrite.rgb(15, 15, 15, '%'),
    font_size='15px',
    font_weight="bold")
)

# lets draw a smiley face
# draw a yellow circle
dwg.add(dwg.circle(center=(520,220),
    r=90,
    stroke=svgwrite.rgb(10, 10, 16, '%'),
    fill='yellow')
)
# draw the left then right eye
dwg.add(dwg.circle(center=(495,195),
    r=10,
    stroke=svgwrite.rgb(10, 10, 16, '%'),
    fill='black')
)
dwg.add(dwg.circle(center=(550,195),
    r=10,
    stroke=svgwrite.rgb(10, 10, 16, '%'),
    fill='black')
)

# draw a cubic-bezier-curve path from 470,240 to 570,240
# using control points 490,290 & 550,290
dwg.add(dwg.path( d='M470,240 C490,290, 550,290, 570,240',
    stroke="#000",
    fill="none",
    stroke_width=12)
)

# output our svg image as raw xml
print(dwg.tostring())

# write svg file to disk
dwg.save()

Generated SVG Image

svg example

SVG Source

<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:ev="http://www.w3.org/2001/xml-events" xmlns:xlink="http://www.w3.org/1999/xlink" baseProfile="tiny" height="100%" version="1.2" width="100%">
   <defs>
      <linearGradient id="vert_lin_grad" x1="0" x2="0" y1="0" y2="1">
         <stop offset="0%" stop-color="blue" />
         <stop offset="50%" stop-color="green" />
         <stop offset="100%" stop-color="yellow" />
      </linearGradient>
   </defs>
   <rect fill="red" height="200" stroke="rgb(10%,10%,16%)" width="300" x="10" y="10" />
   <circle cx="25" cy="25" fill="white" r="10" stroke="rgb(15%,15%,15%)" />
   <text fill="rgb(15%,15%,15%)" font-size="15px" font-weight="bold" stroke="none" x="21" y="30">1</text>
   <text fill="#900" font-family="Arial" font-size="90px" font-weight="bold" stroke="none" x="55" y="125">ABC</text>
   <text fill="#A90690" font-family="Courier New" font-size="66px" font-weight="bold" stroke="#500" stroke-width="2" x="50" y="180">12345</text>
   <text fill="white" x="40" y="40">rectangle w/ black stroke &amp; red fill</text>
   <rect fill="none" height="190" stroke="rgb(10%,10%,16%)" width="300" x="10" y="220" />
   <text fill="black" x="40" y="250">rectangle w/ black stroke &amp; no fill</text>
   <circle cx="26" cy="235" fill="#eeeeee" r="10" stroke="rgb(15%,15%,15%)" />
   <text fill="rgb(15%,15%,15%)" font-size="15px" font-weight="bold" stroke="none" x="22" y="240">2</text>
   <rect fill="url(#vert_lin_grad)" height="120" stroke="rgb(10%,10%,16%)" width="240" x="35" y="270" />
   <text fill="white" x="60" y="330">rectangle w/ linear gradient</text>
   <rect fill="blue" height="400" stroke="rgb(10%,10%,16%)" width="400" x="320" y="10" />
   <text fill="yellow" x="360" y="40">rectangle w/ black stroke &amp; blue fill</text>
   <circle cx="335" cy="25" fill="#eeeeee" r="10" stroke="rgb(15%,15%,15%)" />
   <text fill="rgb(15%,15%,15%)" font-size="15px" font-weight="bold" stroke="none" x="331" y="30">3</text>
   <circle cx="520" cy="220" fill="yellow" r="90" stroke="rgb(10%,10%,16%)" />
   <circle cx="495" cy="195" fill="black" r="10" stroke="rgb(10%,10%,16%)" />
   <circle cx="550" cy="195" fill="black" r="10" stroke="rgb(10%,10%,16%)" />
   <path d="M470,240 C490,290, 550,290, 570,240" fill="none" stroke="#000" stroke-width="12" />
</svg>

Creating a Line

This code creates an SVG file with a black line and a red line. The black line starts at the position (10, 10) and ends at the position (100, 50). The red line starts at the position (15, 30) and ends at the position (115, 70) and has a thicker stroke-width of 5.

import svgwrite

# Create a new SVG drawing
dwg = svgwrite.Drawing('02_lines.svg', profile='tiny', size=("12cm", "4cm"), viewBox="0 0 1200 400")

# Show outline of viewport using 'rect' element
dwg.add(dwg.rect(insert=(1, 1), size=("1198", "398"), fill="none", stroke="blue", stroke_width=2))

# Create a group of lines with green stroke
g = dwg.g(stroke="orange")

# Add lines to the group
g.add(dwg.line(start=(100, 300), end=(300, 100), stroke_width=5))
g.add(dwg.line(start=(300, 300), end=(500, 100), stroke_width=10))
g.add(dwg.line(start=(500, 300), end=(700, 100), stroke_width=15))
g.add(dwg.line(start=(700, 300), end=(900, 100), stroke_width=20))
g.add(dwg.line(start=(900, 300), end=(1100, 100), stroke_width=25))

# Add the group to the SVG
dwg.add(g)

# Save the SVG to a file
dwg.save()
how to draw lines with svgwrite

Creating a Circle

This code creates an SVG file with a red circle at the center (50, 50) with a radius of 30.

import svgwrite

dwg = svgwrite.Drawing('03_circle.svg', profile='tiny')
circle = dwg.circle(center=(50, 50), r=30, fill='red')
dwg.add(circle)
dwg.save()
how to draw circles with svgwrite

Creating Text

This code creates an SVG file with the text ‘Hello SVGWrite!’ at the position (10, 30) in blue color.

import svgwrite

dwg = svgwrite.Drawing('04_text.svg', profile='tiny')
text = dwg.text('Hello SVGWrite!', insert=(10, 30), fill='blue')
dwg.add(text)
dwg.save()
how to draw text with svgwrite

Rounded Rectangle

This code creates an SVG file with a green rectangle with rounded corners. The rectangle’s top-left corner is at the position (10, 10), and its size is 100x50. The rx and ry parameters specify the x-axis and y-axis radii of the ellipse used to round off the corners of the rectangle.

import svgwrite

dwg = svgwrite.Drawing('05_rounded_rectangle.svg', profile='tiny')
rectangle = dwg.rect(insert=(10, 10), size=(100, 50), rx=10, ry=10, fill='green')
dwg.add(rectangle)
dwg.save()
how to draw rounded rectangles with svgwrite

Creating an Ellipse

This code creates an SVG file with a purple ellipse. The ellipse’s center is at the position (50, 50), and its radii are 30 (x-axis) and 20 (y-axis).

import svgwrite

dwg = svgwrite.Drawing('06_ellipse.svg', profile='tiny')
ellipse = dwg.ellipse(center=(50, 50), r=(30, 20), fill='purple')
dwg.add(ellipse)
dwg.save()
How to draw an ellipse with svgwrite

dwg.rect & dwg.circle

import svgwrite

dwg = svgwrite.Drawing('07_rect_circle.svg', profile='tiny')
dwg.add(dwg.rect(insert=(50, 20), size=(100, 60), fill='red'))
dwg.add(dwg.circle(center=(50, 20), r=20, fill='blue'))
dwg.save()
how to use svgwrite.rect() and svgwrite.circle()

svg.viewbox & svg.text

This svgwrite code example draws the text ‘Hello SVGWrite’ positioned at the coordinates (0, 20) and filled with the color black. The viewbox is a rectangle that defines the aspect ratio and coordinate system of the SVG image. In this case, the viewbox is set to have a width and height of 200 units.

import svgwrite

dwg = svgwrite.Drawing('08_viebox_text.svg', profile='tiny')
dwg.viewbox(width=200, height=200)
dwg.add(dwg.text('Hello SVGWrite', insert=(0, 20), fill='black'))
dwg.save()
how to use svgwrite.viewbox()

Bar Chart

This script creates a simple bar chart with 10 bars. The height of each bar is determined randomly.

Note: A library like matplotlib is a better choice for creating svg charts.

import svgwrite
from random import randint

dwg = svgwrite.Drawing("09_bar_chart.svg", profile='tiny')

# Create a bar chart with 10 bars
for i in range(10):
    height = randint(10, 200)  # Random height
    dwg.add(dwg.rect(insert=(i * 30, 200 - height), size=(20, height), fill='blue'))

dwg.save()
how to draw a bar chart with svgwrite

Line Graph

This script creates a simple line graph with 10 points. The y-coordinate of each point is determined randomly.

Note: A library like matplotlib is a better choice for creating svg charts.

import svgwrite
from random import randint

dwg = svgwrite.Drawing("10_line_graph.svg", profile='tiny')

points = [(i * 30, randint(10, 200)) for i in range(10)]  # Generate 10 random points
dwg.add(dwg.polyline(points, stroke='blue', fill='none'))

dwg.save()
how to draw a line graph with svgwrite

Pie Chart

This script creates a pie chart with five sections. The proportions and colors of the sections are defined in the proportions and colors lists, respectively.

Note: A library like matplotlib is a better choice for creating svg charts.

import svgwrite
from math import sin, cos, pi

dwg = svgwrite.Drawing("11_pie_chart.svg", profile='tiny' style="width:600px;height:300px;")

# Define the center and radius of the pie chart
center = (200, 200)
radius = 100

# Define the proportions of the pie chart
proportions = [0.1, 0.2, 0.25, 0.15, 0.3]

# Define the colors for each section
colors = ['red', 'green', 'blue', 'yellow', 'purple']

start_angle = 0
for proportion, color in zip(proportions, colors):
    end_angle = start_angle + 2 * pi * proportion

    # Define the start and end points of the arc
    start_point = (center[0] + radius * cos(start_angle), center[1] + radius * sin(start_angle))
    end_point = (center[0] + radius * cos(end_angle), center[1] + radius * sin(end_angle))

    # Draw the arc
    arc = svgwrite.path.Path(d=f"M {center[0]},{center[1]} L {start_point[0]},{start_point[1]} A {radius},{radius} 0 {'1' if proportion > 0.5 else '0'} 1 {end_point[0]},{end_point[1]} z", fill=color)
    dwg.add(arc)

    start_angle = end_angle

dwg.save()
how to draw a pie chart with svgwrite

Grid of Circles

This script creates a 10x10 grid of circles. Each circle is positioned 20 units apart from its neighbors.

import svgwrite

dwg = svgwrite.Drawing("12_grid_of_circles.svg", profile='tiny')

# Create a 10x10 grid of circles
for i in range(10):
    for j in range(10):
        dwg.add(dwg.circle(center=(i * 20 + 10, j * 20 + 10), r=8, fill='red'))

dwg.save()
how to draw a grid of circles with svgwrite

Checkerboard Pattern

This script creates an 8x8 checkerboard pattern. Each square is 30 units wide and high.

import svgwrite

dwg = svgwrite.Drawing("13_checkerboard.svg", profile='tiny')

# Create a 8x8 checkerboard pattern
for i in range(8):
    for j in range(8):
        if (i + j) % 2 == 0:
            dwg.add(dwg.rect(insert=(i * 30, j * 30), size=(30, 30), fill='black'))

dwg.save()
how to draw a checkboard pattern with svgwrite

Spiral Pattern

This script creates a spiral pattern with 1000 points. The position of each point is determined by a simple spiral equation.

import svgwrite
from math import sin, cos, pi

dwg = svgwrite.Drawing("14_spiral.svg", profile='tiny')

# Create a spiral pattern with 100 points
points = [(200 + i * cos(i / 10), 200 + i * sin(i / 10)) for i in range(1000)]
dwg.add(dwg.polyline(points, stroke='blue', fill='none'))

dwg.save()
how to draw a spiral pattern with svgwrite

Radial Gradient

How to draw a shape filled with a color gradient using svgwrite. This script creates a circle filled with a radial gradient. The gradient transitions from red at the center to blue at the edge.

import svgwrite

dwg = svgwrite.Drawing("15_gradient.svg", profile='tiny')

# Create a radial gradient
gradient = dwg.radialGradient()
dwg.defs.add(gradient)
gradient.add_stop_color(0, 'red')
gradient.add_stop_color(1, 'blue')

# Draw a circle with the gradient
dwg.add(dwg.circle(center=(200, 200), r=100, fill=gradient.get_paint_server()))

dwg.save()
how to draw a shape filled with a color gradient using svgwrite

Text using Fonts

This example code creates an SVG image with the text ‘Hello Veranda’ at the position (20, 50). The text is displayed in the ‘Verdana’ font, with a font size of 30, and in black color. The SVG image is then saved to ’text_with_font.svg’.

Please note that the availability of the ‘Verdana’ font (or any other font you specify) depends on the system where the SVG image is viewed. If the specified font is not available on the system, a default font will be used instead.

import svgwrite

dwg = svgwrite.Drawing('16_text_with_font.svg', profile='tiny')
dwg.viewbox(minx=0, miny=0, width=400, height=600)  # Correct usage of viewbox

# List of common font faces
font_faces = ['Arial', 'Courier New', 'Georgia', 'Times New Roman', 'Verdana', 'Comic Sans MS']

# Create a text element for each font face
for i, font_face in enumerate(font_faces):
    text = svgwrite.text.Text(f'Hello {font_face}', insert=(20, 50 + i * 60), fill='black')  # Adjust the y-coordinate for each text
    text['font-size'] = '30px'
    text['font-family'] = font_face
    dwg.add(text)

# Save the drawing to a file
dwg.save()
how to draw text using a specific font with svgwrite

Gradient filled Text

This code creates an SVG image with the text ‘Colorful Text using clip-path’ filled with a colorful gradient using clip-path. The text is displayed in the ‘Arial Bold’ font, with a font size of 36. The SVG image is then saved to ‘17_gradient_text.svg’.

import svgwrite

# Create a new SVG drawing
dwg = svgwrite.Drawing('17_gradient_text.svg', profile='full')

# Define the linear gradient
gradient = dwg.defs.add(dwg.linearGradient(id="gradient"))
gradient.add_stop_color("10%", "#e82164")
gradient.add_stop_color("50%", "#fdc013")
gradient.add_stop_color("90%", "#488fcc")

# Create a text element with Arial Bold font
text = dwg.text("Colorful Text using clip-path", insert=(50, 75), font_size="36", 
                fill="url(#gradient)", font_family="Arial", font_weight="bold")


# Define the clip path
clip_path = dwg.defs.add(dwg.clipPath(id="clip"))
clip_path.add(text)

# Add a rectangle that uses the clip path
dwg.add(dwg.rect(insert=(0, 20), size=("100%", "100%"), fill="url(#gradient)", clip_path="url(#clip)"))

# Save the SVG to a file
dwg.save()
how to draw text with a gradient fill color with svgwrite

Curved Text along a path

This code creates an SVG image with the text ‘Hello SVGWrite’ along a path defined by the “M 100 100 Q 200 50 300 100 T 500 100” command. The text is displayed in the ‘Verdana’ font, with a font size of 20. The SVG image is then saved to ’text_path.svg’.

import svgwrite

dwg = svgwrite.Drawing('18_text_path.svg', profile='tiny')
dwg.viewbox(width=400, height=200)

# Define a path
path = dwg.path(d="M 100 100 Q 200 50 300 100 T 500 100", id="path")

# Add the path to the defs section of the SVG
dwg.defs.add(path)

# Create a textPath element, specify the font, font size, and link it to the path
text_path = svgwrite.text.TextPath("#path", "Hello SVGWrite")
text = svgwrite.text.Text("", fill="black")
text.font_size = 20
text.font_family = 'Verdana'
text.add(text_path)

# Add the text element to the drawing
dwg.add(text)

# Save the drawing to a file
dwg.save()
how to draw text along a path with svgwrite

Clipping Path Example

This code creates an SVG image demonstrating how to use clip-path with svgwrite. First we create two circles and use one as the clip-path for the second circle. The resulting shape resembles a lemon. We proceed to create second slightly larger lemon shape using two more circles.

import svgwrite

dwg = svgwrite.Drawing('19_clip_example.svg', profile='full')
dwg.viewbox(width=400, height=200)

# Background color
dwg.add(dwg.rect(insert=(0, 0), size=('100%', '100%'), rx=None, ry=None, fill='rgb(128,128,128)'))

# Create a Lemon shape using clip-path

# Create two circles
circle1 = dwg.circle(center=(75, 75), r=50, fill="yellow")
circle2 = dwg.circle(center=(100, 100), r=50, fill="yellow")

# Define a clip path
clip_path_a = dwg.defs.add(dwg.clipPath(id="clip-a"))
clip_path_a.add(circle1)

# Apply the clip path to circle2
circle2['clip-path'] = 'url(#clip-a)'

# Add circle2 to the drawing
dwg.add(circle2)


# Create another Lemon shape using clip-path

# Create two more circles
circle3 = dwg.circle(center=(275, 75), r=60, fill="yellow")
circle4 = dwg.circle(center=(300, 100), r=60, fill="yellow")

# Define a clip path
clip_path_b = dwg.defs.add(dwg.clipPath(id="clip-b"))
clip_path_b.add(circle3)

# Apply the clip path to circle2
circle4['clip-path'] = 'url(#clip-b)'

# Add circle4 to the drawing
dwg.add(circle4)

# Save the drawing to a file
dwg.save()
how to draw use a clipping path with svgwrite

Union of two shapes

In this example, the two circles overlap, creating a union-like effect where they intersect. However, this is not a true union operation, as the overlapping area is a different color due to the overlap of the two circles. For more complex operations, you would need to use a library like shapely to calculate the resulting shape of the operation, and then add that shape to the SVG.

import svgwrite

dwg = svgwrite.Drawing('20_union_example.svg', profile='tiny')
dwg.viewbox(width=400, height=200)

# Create two overlapping circles
circle1 = dwg.circle(center=(100, 100), r=100, fill='red')
circle2 = dwg.circle(center=(200, 100), r=100, fill='blue')

# Add the circles to the drawing
dwg.add(circle1)
dwg.add(circle2)

# Save the drawing to a file
dwg.save()
svgwrite example: union of two cicles with svgwrite

Heart-Shaped Path

import svgwrite

dwg = svgwrite.Drawing('21_heart_path.svg', profile='tiny')

# Create a heart shape using a path
heart_path = dwg.path(d="M10,30 A20,20,0,0,1,50,30 A20,20,0,0,1,90,30 Q90,60,50,90 Q10,60,10,30 Z", 
                      id="heart", fill="red")

dwg.add(heart_path)
dwg.save()
svgwrite example: union of two cicles with svgwrite

Repeating Patterns

To create repeating patterns with svg we first define a pattern with a size of 50 x 50. Next, we add several shapes to the pattern. Finally we draw rectangle but supply the pattern id to the fill property.

import svgwrite

# Create a new SVG drawing
dwg = svgwrite.Drawing('22_repeating_patterns.svg')

# Define the pattern
pattern = dwg.defs.add(dwg.pattern(size=(50, 50), patternUnits="userSpaceOnUse", id="pattern"))

# Add a blue circle to the pattern
pattern.add(dwg.circle(center=(10, 10), r=10, fill='blue'))

# Add a yellow circle to the pattern
pattern.add(dwg.circle(center=(10, 10), r=7, fill='yellow'))

# Add a red rectangle to the pattern
pattern.add(dwg.rect(insert=(30, 30), size=(10, 10), fill='red'))

# Add a another rectangle to the pattern
pattern.add(dwg.rect(insert=(25, 25), size=(20, 20), stroke='orange', fill='none'))

# Add a another rectangle to the pattern
pattern.add(dwg.rect(insert=(22, 22), size=(26, 26), stroke='green', fill='none'))

# Add a another rectangle to the pattern
pattern.add(dwg.rect(insert=(10, 10), size=(20, 20), stroke='red', fill='none'))

# Create a rectangle and apply the pattern
rect = dwg.rect(insert=(0, 0), size=("100%", "100%"), fill="url(#pattern)")

# Add the rectangle to the SVG
dwg.add(rect)

# Save the SVG to a file
dwg.save()
svgwrite example: union of two cicles with svgwrite

About svgwrite

svgwrite - A Python library to create SVG drawings.