Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 3.3 — A Bar Chart in Plain SVG
Data Visualization · Example 1 of 3

drawBars: negative values and a zero line

The orange bars are negative. Labels of negative bars sit above the zero line, so they never run into the bars.

Build a bar chart from data with a loop: one SVG rectangle per row, with bar width and position worked out from the number of bars. Then meet the cases that break it: zero, negative and missing values, long names and sorting.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Make the monthly bar chart show the value labels with a thousands separator (for example 117,803 instead of 118k), and say what happens to the layout on a 12-bar chart.

02

Write bandX(i, count, width, gapShare) that returns { x, barWidth } for bar i. Test it with (0, 12, 460, 0.2) and (11, 12, 460, 0.2).

03

What should the chart do for an empty array of rows? Write the check and the message.

Explain it without notes

01

How do you work out each bar's x position and width from the number of bars?

02

Why does a bar's y attribute not hold its height, and how do you draw a bar that goes below the zero line?

03

What is the difference between a value of 0 and a missing value, and how should each look in the chart?

04

Why measure the labels before choosing the left margin of a horizontal bar chart?

drawBars: negative values and a zero line

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

domain -18996 to 10091 - the zero line is at y = 65.9
Bars: 7 - heights: 51 66 59 107 104 124 79