D3 Examples

Richard Dalton

Data Driven Documents

D3 allows document elements to be generated from data. Hence the name Data Driven Documents (D3).

In the example below, and array of json key-value pairs are rendered as headings and paragraphs. We append a div for each data item, and then within that div we render a heading for the key and a paragraph for the value.

    data = [
        {"key": "First Heading", "value":"First Paragraph"},
        {"key": "Second Heading", "value":"Second Paragraph"},
        {"key": "Third Heading", "value":"Third Paragraph"},
        {"key": "Fourth Heading", "value":"Fourth Paragraph"},
        {"key": "Fifth Heading", "value":"Fifth Paragraph"},
    ];

    //Create SVG element
    var doc = d3.select("#draw_here");

    var doc_item = doc.selectAll("div")
            .data(data)
            .enter()
            .append("div");

    doc_item.append("h4").text(function (d) {
                return d.key;
            });

    doc_item.append("p").text(function (d) {
        return d.value;
    })