Skip to content

Instantly share code, notes, and snippets.

@codetricity
Last active August 24, 2018 13:26
Show Gist options
  • Select an option

  • Save codetricity/e40b2361e4e69b6908324de63afd9f55 to your computer and use it in GitHub Desktop.

Select an option

Save codetricity/e40b2361e4e69b6908324de63afd9f55 to your computer and use it in GitHub Desktop.

Bar Chart

  1. reverse linear scale output (range)
  2. set starting y coordinate of rectangle to be length height of reversed rectangle
  3. adjust height of each rectangle in bar chart

bar chart

Reverse Linear Scale

var y = d3.scaleLinear()
    .domain([0, max2])
    .range([400, 0]);

reverse bar chart

Part we want

Adjust y coordinate

.attr("y", function(d){
    return y(d.population);
})

y coordinate

height problem

Adjust height

.attr("height", function(d){
    var height = 450 - y(d.population);
    console.log(height)
    return height;
})

final chart


SVG Group

group is the "g" tag. transform moves things translate moves in x, y direction rotate

var svg = d3.select("#canvas")
    .append("g")
    .attr("transform", "translate(200, 0)");

translate

Exercises

  • change x and y translation values

Challenge

rotate

Hint: transform, rotate(degrees, x, y)

translate with margin

var margin = {right: 100, left: 100, top: 10, bottom: 100};

var svg = d3.select("#canvas")
    .append("g")
    .attr("transform", "translate(" + 
        margin.right + 
        ", " +
        margin.top + ")");

Text Labels

labels

svg.selectAll("text")
    .data(data)
    .enter()
    .append("text")
        .attr("y", function(d, i){
            return 10 + (i * 15)
        })
        .attr("x", function(d, i){
            return i * 30
        })
        .text(function(d){
            var name = d.name;
            console.log(name);
            return name;
        });

Next Tutorial

http://alignedleft.com/tutorials/d3/making-a-bar-chart/

Using D3 v3, though v4 should work

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment