generated at
d3-axis
を描画するD3.jsのmodule
SVGで横軸を組み立てているだけ
JSXで書き換えられそうtakker

概略
引数にScale (d3)を渡す
scaleをAxis.scale()であとから変更できる
Axis(selection) と関数で呼び出すと、 selection で指定されたDOMに対して軸を描画する

1. 横軸を作る
ex1.js
const { render, html } = htmPreact; const { axisBottom, select, scaleLinear } = d3; const [width, height] = [600, 100]; render(html`
描画領域の設定
ex1.js
<svg xmlns="http://www.w3.org/2000/svg" width=${width} height=${height}>
svg g に描画する
縦方向に中央揃えしておく
ex1.js
<g transform=${`translate(0, ${height / 2})`} ref=${(g) => {
d3-scaleで軸の範囲と長さを設定する
ex1.js
const padding = 20; const scale = d3.scaleLinear().domain([0, 100]).range([padding, width - padding]);
ここでは、値の範囲が0から100まで、描画範囲が20pxから580pxまでに設定された
svg の両端から20px離して描画するようにした
この位置設定もCSSかSVGのtransformで完結させられないかな?takker
axisBottom で横軸を描画する関数 Axis https://doc.deno.land/https://cdn.skypack.dev/-/d3-axis@v3.0.0-atdNID4TA9Y0wR53lsTq/dist=es2019,mode=types/index.d.ts/~/Axis を作り、 select(g) (= select("svg g") )にrenderする
ex1.js
const axis = axisBottom(scale); axis(select(g));
axis(select(g)) は通常 select(g).call(axis) と書く
短く axisBottom(scale)(select(g)) とも書ける
ex1.js
}}/> </svg>`, document.body);

「1. 横軸を作る」の位置設定をSVG transformだけでしてみる
2023-02-07 11:40:37 無理だった
SVG transform 50% のような指定ができない
自分のコンテナに合わせた座標変換が不可能
ex1-1.js
const [width, height] = [600, 100]; document.body.insertAdjacentHTML("beforeend",` <svg xmlns="http://www.w3.org/2000/svg" width=${width} height=${height}> <g transform="translate(${width / 2}, ${height / 2})"> <g transform="translate(0, ${height / 2})" /> </g> </svg> `); const { axisBottom, select, scaleLinear } = d3; const scale = d3.scaleLinear().domain([0, 100]).range([0, 100]); const axis = axisBottom(scale); axis(select("svg g g"));

目盛りの間隔を調整する
Axis.tickArguments() と同じ効果
ticks() が無いときは無視される
tickFormat() が無いときは (x) => x が使われる
Scale のこれらの値は、 Axis を実行する際にresetされてしまうので、 Axis.ticks() で設定する必要がある
例:20ごとに目盛りを打つ
ex-ticks.js
const [width, height] = [600, 100]; document.body.insertAdjacentHTML("beforeend",` <svg xmlns="http://www.w3.org/2000/svg" width=${width} height=${height}> <g transform="translate(0, ${height / 2})" /> </svg> `); const { axisBottom, select, scaleLinear } = d3; const padding = width / 30; const scale = scaleLinear().domain([0, 100]).range([padding, width - padding]); const axis = axisBottom(scale) .ticks(100 / 20); axis(select("svg g"));

references

axis.ts
export * from "https://cdn.skypack.dev/d3-axis@v3.0.0?dts";

#2023-04-08 20:50:14
#2023-02-07 14:31:33
#2023-02-05 11:04:24