###### tags `技術書典すぎもと組` # ロリポップ ## 完成形 2点のあいだを線でむすんだかわいいロリポップチャートを作成します。 <img src="https://i.imgur.com/fRpnIfo.png" width="50%"> 描画する範囲指定します w = 600; // 幅の指定 h = 600; // 高さの指定 余白を設定します margin = ({ top: 10, right: 40, bottom: 20, left: 30 }) ## データの作成 使うデータを定義します。 今回は、ひとつのグループ(group)が2つの値(value1,value2)を持っているので、以下のようにデータを設定します dataset = [ {group:1, value1:17, value2:20}, {group:2, value1:17, value2:18}, {group:3, value1:11, value2:18}, {group:4, value1:10, value2:17}, {group:5, value1:10, value2:12}, {group:6, value1:9, value2:15}, {group:7, value1:7, value2:10}, {group:8, value1:7, value2:9}, {group:9, value1:5, value2:6}, {group:10, value1:0, value2:3} ]; ### x軸のスケール設定 x軸には「scaleLinear」を利用する。「scaleLinear」は配列を与えることで、指定した範囲にマップする関数を作成してくれます。 const x = d3.scaleLinear() .domain([-2, 22]) .range([0, w - margin.right]) // [ -2から22 ] の数字を [ 0からw - margin.right ]の位置に当てはめます ### y軸のスケール設定 y軸には「scaleLinear」を利用する。「scaleLinear」は実数範囲を実数範囲に割り当てることができます。 const y = d3.scaleBand() .domain(dataset.map(function(d) { return d.group; })) .range([0, h]) .padding(1) // 間隔を調整 // [ groupの全部の数字 ]を[ 0からh ]の位置に当てはめます ## チャートの作成 ### 幅600px×高さ600pxのsvgを描画します。 const svg = d3.create("svg").attr("viewBox", [0, 0, w, h]); return svg.node(); // svgを( w × h )の範囲で描画します ### 線の描画 value1とvalue2をつなぐ線を引きます。 d3.select(svg).selectAll("line") .data(dataset) //datasetからデータを取ってきます .enter() .append("line") // 線を引きます .attr("x1", function(d) { return x(d.value1) + margin.left;}) .attr("x2", function(d) { return x(d.value2) + margin.left;}) .attr("y1", function(d) { return y(d.group) - margin.bottom;}) .attr("y2", function(d) { return y(d.group) - margin.bottom;}) .attr("stroke", "black") // 線の色の指定 .attr("stroke-width", "2px") // 線の太さの指定 ### 左円の描画 value1の円を描写していきます。 d3.select(svg).selectAll("circle1") .data(dataset) .enter() .append("circle") // 円を描きます .attr("cx", function(d) { return x(d.value1) + margin.left }) .attr("cy", function(d) { return y(d.group) - margin.bottom}) .attr("r", "8") // 円の半径を指定 .attr("fill", "#4baea0") // 円の中の色の指定 ### 右円の描画   value2の円を描写していきます。 d3.select(svg).selectAll("circle2") .data(dataset) .enter() .append("circle") // 円を描きます .attr("cx", function(d) { return x(d.value2) + margin.left }) .attr("cy", function(d) { return y(d.group) - margin.bottom}) .attr("r", "8") // 円の半径を指定 .attr("fill", "#315b96") // 円の中の色の指定 ### x軸の目盛の描画   「d3.axisBottom」をcall関数で呼び出すことによりx座標を描きます。 d3.select(svg) .append("g") .attr("transform", "translate(" + margin.left + "," + (h - margin.bottom) + ")") .attr("stroke-width", "2px") // 座標の線の太さ .call(d3.axisBottom(x))// axisBottomをcall関数で呼び出す ### y軸の目盛の描画   「d3.axisLeft」をcall関数で呼び出すことによりy座標を描きます。 d3.select(svg) .append("g") .attr("transform", "translate(" + margin.left + "," + (-margin.bottom) + ")") .attr("stroke-width", "2px") // 座標の線の太さ .call(d3.axisLeft(y))// axisLeftをcall関数で呼び出す これで完成!!!!!