D3.jsで横向きのBar Graph(棒グラフ)を描画する

横向きの棒グラフを描画する

コードを確認

説明

// データセット
const dataSet = [100, 200, 20, 45, 300];
// グラフを描画する
drawGraph(dataSet);

function drawGraph(dataSet) {
  const maxValue = Math.max(...dataSet);

  const OriginAttr = {
    fill: "rgba(255, 0, 0, 0)"
  };

  d3.select("#graphArea")
    .selectAll("rect")                              // 対象要素を設定
    .data(dataSet)                                  // データセットを設定
    .enter()                                        // データ数に応じて要素を追加
    .append("rect")                                 // SVGの四角形を作成
    .attr("x", 0)                                   // X座標(始点)
    .attr("y", (d, i) => {
      return i * 25;
    })                                              // Y座標(各データセットの描画位置)
    .attr("width", (d, i) => {
      return `${d}px`;
    })                                              // 横棒グラフの横幅(X座標の終点)
    .attr("height", "20px")                         // 横棒グラフの高さ
    .attr("fill", (d, i) => {
      return `rgba(255, 0, 0, ${d / maxValue})`;
    })                                              // 棒グラフの色
    .on("mouseover", function () {
      OriginAttr.fill = this.attributes.fill.value; // 変更前の状態を記憶
      d3.select(this)
        .attr("fill", "blue");                      // 選択されたグラフの色を変更
    })
    .on("mouseout", function () {
      d3.select(this)
        .attr("fill", OriginAttr.fill);             // 変更前の状態に戻す
    });
}