LoginSignup
0
0

More than 3 years have passed since last update.

[D3.js] たのしいグラフ描画 - ラベル位置を工夫した円グラフ

Posted at

D3.jsを使って単純な円グラフを描画します。ラベルも付けてみます。

元データ

元データです。
キーと値のハッシュになっています。

testdata = {
  水分: 95.4,
  タンパク質: 1.0,
  脂質: 0.1,
  炭水化物: 3.0,
  灰分: 0.5
}

できあがりイメージ

グラフの右側にラベルを置き、円弧と線で結んでみました。

image.png

プログラム

プログラムの一部です。

線分は d3.lineRadical でひきました。
lineRadicalに渡す値は、以下のように計算しました。

  const calcLineRadical = d => {
    const firstAngle = d.midAngle;
    const firstRadius =
      (d.xOrder * 30) / Math.abs(Math.cos(Math.PI - firstAngle));
    const xpos = radius * 1.5 - d.centroidX;
    const secondAngle =
      Math.PI + Math.atan(xpos / (firstRadius * Math.cos(firstAngle)));
    const secondRadius = Math.abs(xpos / Math.sin(secondAngle));
    const fixedSecondAngle =
      secondAngle < Math.PI ? secondAngle : secondAngle - Math.PI;

    return [
      [0, 0],
      [firstAngle, firstRadius],
      [fixedSecondAngle, secondRadius]
    ];
  };

プログラム全体はObservableに置いています。

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