How shapes are drawn into SVG
The top left corner is the origin or the (0,0) point in an SVG coordinate system. The positive x-axis points towards the right, the positive y-axis points down. Thus, if we draw a circle element with its center is placed as cx="0"
and cy="0"
will be placed on the left corner.
<svg viewBox="0 0 500 250">
// Add a yellow circle to (0,0) point.
<circle cx="0" cy="0" r="10" fill="yellow" />
</svg>
This has implications when we want to map our data into an SVG like in a typical x-y chart we learn at school where the 0,0 point is at the left bottom.
What d3 scale functions does is to map a domain of data values to a range of pixel dimensions in our SVG element.
In this example, our domain is data values between [0,120]
and our range is [0,250]
the height of the SVG which is 250 pixels. For example a value of 60 will be mapped to 125 pixels in our svg element.
<script>
import { scaleLinear } from 'd3-scale';
const data = [20, 80, 120];
$: y = scaleLinear().domain([0, 100]).range([0, height]);
{#each [20, 80, 120] as d}
<circle cx="0" cy={y(d)} r="15" fill="red" />
<text
x="0"
y={y(d)}
class="fill-gray-100"
text-anchor="middle"
font-size="12px"
dominant-baseline="middle">{d}</text>
{/each}
</script>
When we look at the points the bigger the values it is more at the bottom, to make this look like a classical x-y chart we need to reverse the range
in our scale function from 0 -> height
to height -> 0
. What this will do is to map the (0,0) point to left bottom of our chart and we will see that the points with bigger values are placed at the top.
<script>
//
$: y = scaleLinear().domain([0, 100]).range([height, 0]);
</script>
Drawing a bar
Let’s draw a rect element in our SVG. Rect element starts with its top left corner at x-y point and drawn towards right and below with the width and height attributes respectively. This will be important if we want to animate the bars.
<rect x="80" y="50" width="50" height="150" fill="yellow" />
Follow along the tutorials to find out how to create and animate vertical bar charts.