Skip to content

Latest commit

 

History

History
115 lines (91 loc) · 2.57 KB

00-bar-chart.md

File metadata and controls

115 lines (91 loc) · 2.57 KB

bar-chart

Here's a basic bar chart:

import { select } from "d3";
import { build, BarChart } from "@michigandaily/bore";
const draw = () => {
  const figure = select("figure");

  const data = new Map()
    .set("A", 5)
    .set("B", 2)
    .set("C", 2)
    .set("D", 10)
    .set("E", 4)
    .set("F", 1)
    .set("G", 20);

  figure.append("svg")
    .datum(data)
    .call(
      build(
        new BarChart()
      )
    );
}

The bar chart data has to be a Map data structure. However, we typically deal with arrays and objects. We'll need to convert these data structures to maps.

Consider the following CSV file of tidy data:

key,value
A,5
B,2
C,2
D,10
E,4
F,1
G,20

Here's how we can still use BarChart.

  1. Import your CSV:

    import datafile from "../data/data.csv";
    
    // d3.autoType infers ISO 8601 strings and numbers into the correct JavaScript types
    const csvdata = await d3.csv(datafile, d3.autoType);
    
    // After reading the CSV file with `d3.csv`, we get the following as `data`:
    // [
    //   { key: "A", value: 5 },
    //   { key: "B", value: 2 },
    //   { key: "C", value: 2 },
    //   { key: "D", value: 10 },
    //   { key: "E", value: 4 },
    //   { key: "F", value: 1 },
    //   { key: "G", value: 20 }
    // ]
  2. Use the map function to convert the data into something usable by the Map constructor:

    // We can convert this array of objects to a map by doing the following:
    
    const data = csvdata.map((d) => [d.key, d.value]);
    
    // That gives us the following structure:
    
    // [
    //   ["A", 5],
    //   ["B", 2],
    //   ["C", 2],
    //   ["D", 10],
    //   ["E", 4],
    //   ["F", 1],
    //   ["G", 20],
    // ];
  3. Then we can use the Map constructor:

    new Map(data)

Here's it all put together:

import { csv, autoType, select } from "d3";
import { build, BarChart } from "@michigandaily/bore";
import datafile from "../data/data.csv";

const draw = async () => {
  const csvdata = await csv(datafile, autoType);
  const data = csvdata.map((d) => [d.key, d.value]);

  const figure = select("figure");
  figure.append("svg")
    .datum(new Map(data))
    .call(
      build(
        new BarChart()
      )
    );
};

d3.group, d3.rollup, and d3.index are also very helpful d3 functions that can convert data into a Map.