7
6

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 軸と軸ラベル の微調整テク

Last updated at Posted at 2018-04-05

よく使うテクをまとめたよ。バージョンは 4.X

tick.png

// input
const sc = d3.scaleLinear().domain([0,100]).range([0, width-80]);

const ax = d3.axisBottom().scale(sc);
const ax2 = d3.axisBottom().scale(sc).ticks(4);
const ax3 = d3.axisBottom().scale(sc).tickValues([0,20, 40, 80]);
const ax4 = d3.axisBottom().scale(sc).tickFormat((val) => {
  return val === 30 ? '' : val.toString()
});
const ax5 = d3.axisBottom().scale(sc).tickSize(10)


// output
const x = createOffsetter(30)
const draw = (label, axis) => {
  svg.append('g').append('text').attr('transform', x('label')).text(label)
  return svg.append('g').attr('transform', x('axis')).call(axis)
}

draw('base', ax)
draw('less', ax2)
draw('manual', ax3)
draw('vanish', ax4)
draw('size', ax5)
draw('rotate', ax).selectAll('text')
  .style('text-anchor', 'end')
  .attr('dx', '-1em')
  .attr('dy', '-0.7em')
  .attr('transform', 'rotate(-90)')
draw('emphasize', ax).selectAll('text')
  .style('font-size', (d) => d == 50 ? '20' : '10' )

補足:vanish, emphasize で使っている特定の tick の選択方法は値 d に基づくものだけでなく、コールバックの第二引数である index に紐づけることも可能。

7
6
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
7
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?