Check out bidbear.io Amazon Advertising for Humans. Now publicly available πŸš€

SVG Notes

Intro

Just going to cover some SVG basics before we do a deep dive into the D3 data visualization library.

SVG

As of HTML5 SVG’s are actually HTML elements. Every shape actually has it’s own object in the DOM.

Positioning

Elements are positioned using a co-ordinate system on a grid with the origin in the top left.

svg positions grid

One of the main purposes of D3 is to position elements on these co-ordinates based on the data that we feed it.

The grid is commonly referred to as the viewport or canvas.

Drawing Shapes

With HTML

<svg>
  <rect width="50" height="200" style="fill: blue" />
</svg>

With D3

d3.select("body")
  .append("svg")
  .append("rect")
  .attr("width", 50)
  .attr("height", 200)
  .style("fill", "blue")

Both will make a simple blue rectangle. The tricky part is when we need to make a new rectangle for every piece of data, space them appropriately and transform the shape of the svg relative to the data, etc etc. D3 has all kinds of methods to help with this.

SVG Fill

The <svg> element itself cannot be filled, however if you give it a fill all of the shapes inside the svg will default to that color, unless they are given a specific fill themselves.

<svg width="500" height="500" fill="#fe8d6d">
  <rect
    x="25"
    y="25"
    width="100"
    height="100"
    fill="#544336"
    stroke="#8bc34a"
    stroke-width="6"
  ></rect>
  <circle r="100" cx="250" cy="150">
</svg>

svg fill

Lines

Now we can add a line to this little collage. Lines require a starting coordinate (x1,y1) and ending coordinate (x2,y2) a stroke and stroke width.

<svg width="500" height="500" fill="purple">
  <rect
    x="25"
    y="25"
    width="100"
    height="100"
    fill="#544336"
    stroke="#8bc34a"
    stroke-width="6"
  ></rect>
  <circle r="100" cx="250" cy="150"></circle>>
  <line x1="50" y1="50" x2="200" y2="200" stroke="blue" stroke-width="10"> </line>    
</svg>

line

Path

The SVG path shape is the most powerful shape, as it can make all other shapes, however it has a sort of linear command system that makes it a bit more complicated than the others. Look at the following.

<svg width="500" height="500">
  <path d="M100,100 L300,150" fill="none" stroke="purple" stroke-width="10"></path>
</svg>

path

The fill and stroke stuff is obvious, but with is up with the d="M100,100 L300,150"? This is a sort of virtual stylus, the M stands for move (without drawing anything) and the L makes a line. The numbers are coordinates. So it is saying move the stylus to x=100 y=100 then draw a line to x=300 y=150. Then you can just keep chaining commands after that.

Amazon Ad Analytics For Humans

Advertising reports automatically saved and displayed beautifully for powerful insights.

bidbear.io
portfolios page sunburst chart