###### tags `技術書典すぎもと組`
# 棒グラフ
## 完成形
今回は、下のようなグラフ「棒グラフ」の書き方のご紹介をしていきます。
<img src="https://i.imgur.com/0ZPu92E.png" width="50%">
まずは描画するsvgの範囲指定します。
w = 300; // 幅300pxの指定
h = 300; // 高さ300pxの指定
棒の隙間の範囲も決めておきます。
padding = 5; // 隙間5pxの指定
## データの用意
使うデータを定義します。
dataset = [5, 10, 15, 20, 25, 30, 35];
## 棒グラフの描画
#### ① 幅300px×高さ300pxのsvgを描画します。
svg = {
const svg = DOM.svg(w, h);
return svg
}
// svgを( w × h )の範囲で描画します
#### ② x軸のスケール設定
x軸には「scaleBand」を利用する。「scaleBand」は配列を与えることで、指定した範囲にマップする関数を作成してくれます。
const x = d3.scaleLinear()
.domain([-2, 22])
.range([0, w - 40])
// [ -2から22 ] の数字を [ 0からw - 40 ]に当てはめます
#### ③ y軸のスケール設定
y軸には「scaleLinear」を利用する。「scaleLinear」は実数範囲を実数範囲に割り当てることができます。
const y = d3.scaleBand()
.domain(dataset.map(function(d) { return d.group; }))
.range([0, h])
.padding(1) // 間隔を調整
// [ groupの全部の数字 ]を[ 0からh ]に当てはめます
#### ④ 線の描画
value1とvalue2をつなぐ線を描写していきます。
※ +30,-20は後々出てくる目盛対応して調整しています
.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) + 30 })
// 中心のx座標はvalue1のデータ+30の位置
.attr("cy", function(d) { return y(d.group) - 20})
// 中心のy座標はgroupのデータ-20の位置
.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) + 30 })
// 中心のx座標はvalue2のデータ+30の位置
.attr("cy", function(d) { return y(d.group) - 20})
// 中心のy座標はgroupのデータ-20の位置
.attr("r", "8") // 円の半径を指定
.attr("fill", "#315b96") // 円の中の色の指定
#### ⑦ x軸の目盛の描画
「d3.axisBottom」をcall関数で呼び出すことによりx座標を描きます。
d3.select(svg)
.append("g")
.attr("transform", "translate(" + 30 + "," + (h - 20) + ")")
.attr("stroke-width", "2px") // 座標の線の太さ
.call(d3.axisBottom(x))
axisBottomをcall関数で呼び出す
#### ⑧ y軸の目盛の描画
「d3.axisLeft」をcall関数で呼び出すことによりy座標を描きます。
d3.select(svg)
.append("g")
.attr("transform", "translate(" + 30 + "," + (-20) + ")")
//ここどうやって書けばわかりやすいと思いますか?
.attr("stroke-width", "2px")
// 座標の線の太さ
.call(d3.axisLeft(y))
// axisLeftをcall関数で呼び出す
これで完成!!!!!