🖥

Nuxt3 + javascript d3 ライブラリで散布図を描く ( Compotision API ) ( script setup

2023/09/01に公開

インストール

npm install d3 --save

typescript型管理用

npm i --save-dev @types/d3

とくにnuxt configに何も設定しなくても動く様子

コード例

script直下でd3を利用しようとするとエラーが発生したが onMounted の中に書くことにより動いた

d3のコード部分はほぼ以下参考サイトのまま
https://wizardace.com/d3-scatterplot/

<template>
  <div id="foo">
  </div>
</template>

<script setup lang="ts">
import * as d3 from 'd3'

onMounted(() => {
  var dataset = [
    [5, 20],
    [480, 90],
    [250, 50],
    [100, 33],
    [330, 95],
    [410, 12],
    [475, 44],
    [25, 67],
    [85, 21],
    [220, 88]
  ];

  var width = 400; // グラフの幅
  var height = 300; // グラフの高さ
  var margin = { "top": 30, "bottom": 60, "right": 30, "left": 60 };

  // 2. SVG領域の設定
  var svg = d3.select("#foo").append("svg").attr("width", width).attr("height", height);

  // 3. 軸スケールの設定
  var xScale = d3.scaleLinear()
    .domain([0, d3.max(dataset, function (d) { return d[0]; })])
    .range([margin.left, width - margin.right]);

  var yScale = d3.scaleLinear()
    .domain([0, d3.max(dataset, function (d) { return d[1]; })])
    .range([height - margin.bottom, margin.top]);

  // 4. 軸の表示
  var axisx = d3.axisBottom(xScale).ticks(5);
  var axisy = d3.axisLeft(yScale).ticks(5);

  svg.append("g")
    .attr("transform", "translate(" + 0 + "," + (height - margin.bottom) + ")")
    .call(axisx)
    .append("text")
    .attr("fill", "black")
    .attr("x", (width - margin.left - margin.right) / 2 + margin.left)
    .attr("y", 35)
    .attr("text-anchor", "middle")
    .attr("font-size", "10pt")
    .attr("font-weight", "bold")
    .text("X Label");

  svg.append("g")
    .attr("transform", "translate(" + margin.left + "," + 0 + ")")
    .call(axisy)
    .append("text")
    .attr("fill", "black")
    .attr("x", -(height - margin.top - margin.bottom) / 2 - margin.top)
    .attr("y", -35)
    .attr("transform", "rotate(-90)")
    .attr("text-anchor", "middle")
    .attr("font-weight", "bold")
    .attr("font-size", "10pt")
    .text("Y Label");

  // 5. プロットの表示
  svg.append("g")
    .selectAll("circle")
    .data(dataset)
    .enter()
    .append("circle")
    .attr("cx", function (d) { return xScale(d[0]); })
    .attr("cy", function (d) { return yScale(d[1]); })
    .attr("fill", "steelblue")
    .attr("r", 4);
})

</script>

表示例

<img width="540" alt="image" src="https://user-images.githubusercontent.com/13635059/220295376-2a844285-6340-43d2-b945-d9ce1d25b15c.png">

参考

https://wizardace.com/d3-scatterplot/

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

https://line.me/ti/g2/eEPltQ6Tzh3pYAZV8JXKZqc7PJ6L0rpm573dcQ

Twitter

https://twitter.com/YumaInaura

公開日時

2023-02-21

Discussion