0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

D3.jsで棒グラフを描く

Posted at

昔少し利用したが、すっかり使い方を忘れていたので復習がてらのメモ

インタラクティブな横棒グラフの描画

d3-demo.gif

HTML部分

<!DOCTYPE html>
    <head>
        <meta charset="utf-8">
        <title>グラフ</title>
        <!-- D3.jsの読み込み -->
        <script src="https://d3js.org/d3.v5.min.js"></script>        
    </head>
    <body>
        <!-- グラフ描画するエリア -->
        <svg id="graphArea"></svg>

        <!-- グラフ描画するjs -->
        <script src="js/myGraph.js"></script>
        
    </body>
</html>

Javascript部分


// データセット
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);                              // 変更前の状態に戻す
        });
        
}

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?