nick34992
3/4/2017 - 12:59 AM

D3byEX 6.1: Scatter Plot (Adapted to D3.js v4)

D3byEX 6.1: Scatter Plot (Adapted to D3.js v4)

<!DOCTYPE html>
<html>
    <meta charset=utf-8>
<head>
    <meta name="description" content="D3.js v4, .scaleLinear, scatter plot,
                                      SVG Container, .csv data file" />
</head>
<body>
    <script src="http://d3js.org/d3.v4.js"></script>
    <script src="https://d3js.org/d3-selection-multi.v1.min.js"></script>
    <script>
var url = "https://gist.githubusercontent.com/d3byex/520e6dcb30e673c149cc/raw/432623f00f6740021bdc13141612ac0b6196b022/corr_aapl_msft.csv";
    d3.csv(url, function(error, rawData) {
        var data = rawData.map(function(d) {
            return { X: +d.AAPL, Y: +d.MSFT } // unary oper converts str to int
        });
        var xExtents = d3.extent(data, function (d) { return d.X; });
        var yExtents = d3.extent(data, function (d) { return d.Y; });
        var maxExtent = d3.max(
               xExtents.concat(yExtents), function(d) { return Math.abs(d); });
        var graphWidth = 400, graphHeight = 400;
        var radius = 5;
        var scale = d3.scaleLinear() // v4
            .domain([-maxExtent, maxExtent])
            .range([0, graphWidth]);
        var svg = d3.select('body')
            .append('svg')
            .attrs({width: graphWidth, height: graphHeight});
        svg.selectAll('circle')
            .data(data)
            .enter()
            .append('circle')
            .attrs({ // v4
                cx: function(d) { return scale(d.X); },
                cy: function(d) { return scale(d.Y); },
                r: radius,
                fill: 'steelblue'
            });
    });
    </script>
</body>
</html>