D3 - tutorial Memo

1 minute read

D3

index.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>D3.js</title>
        <style>
            .container {
                width: 250px;
                height: 200px;
                border: 1px solid #720570;
            }

            .bar {
                fill: #720570;
            }
        </style>
        <script src="https://d3js.org/d3.v5.min.js" defer></script>
        <script src="https://d3js.org/d3-scale.v3.min.js" defer></script>
        <script src="app.js" defer></script>
    </head>
    <body>
        <svg></svg>
    </body>
</html>

app.js

// tutorial : https://www.youtube.com/watch?v=TOJ9yjvlapY

// console.log(d3);

const DUMMY_DATA = [
    { id: 'd1', value: 10, region: 'USA' },
    { id: 'd2', value: 11, region: 'India' },
    { id: 'd3', value: 12, region: 'China' },
    { id: 'd4', value: 6, region: 'Germany' },
];

const xScale = d3
    .scaleBand()
    .domain(DUMMY_DATA.map((dataPoint) => dataPoint.region))
    .rangeRound([0, 250])
    .padding(0.1);
const yScale = d3.scaleLinear().domain([0, 15]).range([200, 0]);

const container = d3.select('svg')
    .classed('container', true);

const bars = container
    .selectAll('.bar')
    .data(DUMMY_DATA)
    .enter()
    .append('rect')
    .classed('bar', true)
    .attr('width', xScale.bandwidth())
    .attr('height', (data) => 200 - yScale(data.value))
    .attr('x', data => xScale(data.region))
    .attr('y', data => yScale(data.value));

setTimeout(() => {
    bars.data(DUMMY_DATA.slice(0, 2)).exit().remove();
}, 2000);

SVG

index.html

<!DOCTYPE html>
<html>
    <head>
        <title>Shapes with SVG and CSS</title>
        <link rel="stylesheet" href="styles.css">
    </head>
    <body>
        <svg width="960" height="500">
            <g transform="scale(1.5)">
                <circle cx="50" cy="50" r="40"></circle>
                <rect x="100" y="25" width="50" height="50"></rect>
                <circle cx="50" cy="150" r="40" fill="red"></circle>
                <rect x="100" y="125" width="50" height="50" fill="#e05910"></rect>
                <g transform="translate(0, 200)" fill="#adfffb" stroke="black">
                    <circle cx="50" cy="50" r="40" stroke-width="5"></circle>
                    <rect x="100" y="25" width="50" height="50"></rect>
                </g>

                <g class="lines" transform="translate(50, 0)">
                    <line x1="200" y1="20" x2="300" y2="280"></line>
                    <path fill="none" d="M300 280 L350 200 L400 250 L450 230"></path>
                </g>
            </g>            
        </svg>
    </body>
</html>

styles.css

body {
    margin: 0px;
    overflow: hidden;
}

.lines {
    stroke: black;
    stroke-width: 10;
}

.lines path {
    stroke: #6091fc;
    stroke-linejoin: round;
}