Skip to content

Lesson 5 of 6

Create a Clear Bar Chart with SVG

You write Python code that turns the query results into a simple SVG bar chart saved as an HTML file you can open in a browser.

5 minData Analysis

After this lesson you will be able to turn the query results from the earlier lessons into a simple bar chart saved as an HTML file, and open it in a browser.

What is SVG?

SVG stands for Scalable Vector Graphics. It is a way to describe pictures with text. A browser reads the text and draws the picture. You can write SVG by hand, and you can write Python code that writes SVG text.

A bar chart is a picture that shows amounts as bars. A taller bar means a larger amount. In your sales data, each item has a total revenue. A bar chart can show which item earned the most.

Plan the chart

You already have a Python script that gets items and revenues from the database. In this lesson you will add code that turns those two lists into an SVG bar chart.

The chart needs a title, a bar for each item, and labels so the reader knows what each bar means. The bars will be drawn as rectangles. The height of each rectangle will match the revenue for that item.

Create the SVG text

Start with a new Python file called make_chart.py. It will import sqlite3, run the same query as before, and build the SVG text.

First, get the data and print it to check it is there:

import sqlite3

conn = sqlite3.connect('sales.db')

query = '''
SELECT item, SUM(quantity * unit_price) AS total_revenue
FROM sales
GROUP BY item
ORDER BY total_revenue DESC
'''

results = conn.execute(query).fetchall()

items = []
revenues = []
for row in results:
    items.append(row[0])
    revenues.append(round(row[1], 2))

print(items)
print(revenues)

conn.close()

Run it with python make_chart.py. You should see the same lists as in lesson 4.

Build the SVG string

Now add code that builds a string containing SVG. The string will be written to a file called chart.html.

An SVG image is made of elements. A rectangle is an element. Text is an element. Each element has attributes that say where it goes and how it looks.

The chart will be 400 pixels wide and 300 pixels high. The bars will be drawn from left to right. The tallest bar will be 200 pixels high. The other bars will be scaled to match.

Add this code after the print lines and before conn.close():

max_revenue = max(revenues)
bar_width = 40
gap = 20
chart_height = 300
max_bar_height = 200

svg_parts = []
svg_parts.append(f'<svg width="400" height="{chart_height}" xmlns="http://www.w3.org/2000/svg">')
svg_parts.append('<text x="200" y="30" text-anchor="middle" font-size="20">Total Revenue by Item</text>')

for i in range(len(items)):
    bar_height = (revenues[i] / max_revenue) * max_bar_height
    x = 50 + i * (bar_width + gap)
    y = chart_height - 50 - bar_height
    svg_parts.append(f'<rect x="{x}" y="{y}" width="{bar_width}" height="{bar_height}" fill="steelblue" />')
    svg_parts.append(f'<text x="{x + bar_width / 2}" y="{chart_height - 30}" text-anchor="middle" font-size="12">{items[i]}</text>')
    svg_parts.append(f'<text x="{x + bar_width / 2}" y="{y - 5}" text-anchor="middle" font-size="12">{revenues[i]}</text>')

svg_parts.append('</svg>')

svg_text = '\n'.join(svg_parts)

with open('chart.html', 'w') as f:
    f.write(svg_text)

print('Chart saved to chart.html')

The code works like this. max_revenue is the largest value in the revenues list. Each bar's height is revenues[i] / max_revenue * max_bar_height. So the item with the largest revenue gets a bar 200 pixels high, and the others get smaller bars in proportion.

The x position moves each bar to the right. The first bar starts at 50 pixels from the left. Each bar is 40 pixels wide, and there is a 20 pixel gap between bars.

The y position is measured from the top of the SVG. A larger y means lower on the screen. The bottom of the bars is at chart_height - 50, which is 250. The top of a bar is chart_height - 50 - bar_height.

The code adds three text elements for each bar: the item name below the bar, and the revenue value above the bar.

Finally, the code joins all the SVG parts with newline characters and writes them to chart.html.

Open the chart

Run the script:

python make_chart.py

Then open chart.html in a browser. You should see a bar chart with one bar per item. The item with the highest revenue has the tallest bar. Each bar is labelled with the item name and its revenue.

If you want to change the look, you can change the colours, sizes, or positions in the code. For example, change fill="steelblue" to fill="orange" and run the script again.

Check your understanding

The chart is a simple SVG file. It is not a picture file like a PNG. It is text that the browser draws. You can open chart.html in a text editor and see the SVG elements.

The chart uses the same data as the query in lesson 4. If you change the data in sales.csv and run load_data.py again, then run make_chart.py, the chart will show the new values.

Key takeaways

  • SVG is a text format for pictures that a browser can draw.
  • A bar chart shows amounts as bars; taller bars mean larger amounts.
  • You can write Python code that builds an SVG string and saves it as an HTML file.
  • The height of each bar is scaled so the largest value gets the maximum bar height.
  • Open the HTML file in a browser to see the chart.

Try it

Modify make_chart.py so that the bars are drawn horizontally instead of vertically. The chart should still be 400 pixels wide and 300 pixels high. Each bar should be 20 pixels high, with a 10 pixel gap between bars. The longest bar should be 250 pixels wide. Label each bar with the item name to the left of the bar and the revenue value to the right. Save the chart as chart_horizontal.html. Open it in a browser and check that the item with the highest revenue has the longest bar. A good result is a horizontal bar chart where all bars are visible, labels do not overlap, and the lengths match the revenue values.

Official documentation

Ready to use this in a job?

Rolebound applies to matching roles for you.

Start now

Written with AI and checked automatically. Tools change, so a command may behave differently in the version you install. Spotted a mistake? Tell us.

    Cookies on Rolebound

    We use necessary cookies to sign you in and keep the site working — those cannot be turned off. We would also like to set analytics and advertising cookies so we can see which pages help people get interviews and which adverts brought them here. Nothing optional is set unless you say yes, and you can change your mind at any time from “Cookie settings” in the footer. Read our Privacy Policy.