简体   繁体   中英

Hide selected ticks from displaying on D3.js axis

I'm using D3.js to generate a bar chart with the swiper along the xAxis.

The values that need to be displayed vary from 0 to 1 with the step 0.01, ie I need to display on the bar chart data with the length of 100, ie 100 rects. Example of data to be displayed:

[{"label": 0, "number": 12}, {"label": 0.01, "number": 13}, ..., {"label": 1, "number": 11}]

The problem is there are too many ticks to be displayed and they coincide on each other, looking like this: 图表

What I decided to do was get rid of the labels with the decimals number equal to 2, ie filter only [0, 0.1, 0.2, ..., 1] ticks and display them. After some hacks:

const truncatedXValues = d3Values.filter((item: DashboardBarChartData) =>
  (countDecimals(Number(item.xAxis)) === 1 || countDecimals(Number(item.xAxis)) === 0)
)
this.x = this.x.domain(truncatedXValues.map((item: DashboardBarChartData) => String(item.xAxis)))

This is what I was able to get: 结果

But now since my xAxis is divided into 11 equal parts by D3, when the slider is fully left it is below 0, and when fully right it is above 1, ie ticks do not correspond to the bar that is above it. 结果2

In the screenshot above I displayed by arrows where the labels should be moved, so that the bar that corresponds to the value is right above it.

I suppose I need to make D3 divide the xAxis to the number of all the 100 labels, but hide and display only selected ticks. What is the possible way to do that? Any help is appreciated!

On your axis, use ticks .

const xAxis = d3
  .axisBottom(xScale)
  .ticks(5);  // tells d3 to set around 5 ticks

see working code sample

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM