How can I calculate lines for a custom CartesianGrid in Rechart. How can I remap to the correct domain

1.5k Views Asked by At

CartesianGrid allows me to set the verticalPoints and horizontalPoints to be shown.

Unfortunately, these values are in pixel values on the chart, not in the coordiantes of the x and y domains.

I must be missing something. I have an x-axis and a y-axis. How can I map a value in those domains into positions on the chart?

1

There are 1 best solutions below

2
On BEST ANSWER

So, given some constants defining the chart:

const chartWidth = 600;      // width set on our chart object

const xAxisLeftMargin = 10;  // margins set on our chart object
const xAxisRightMargin = 20;
const xPadding = 0;          // padding set on both sides of xAxis

const yAxisWidth = 120;      // total widths of all yAxes

we can use d3 to create an xScale, like this:

const leftX = 0 + yAxisWidth + xAxisLeftMargin + xPadding;
const rightX = chartWidth - xPadding - xAxisRightMargin;
// note that rightX assumes there are no axes on the right hand side

const xScale = d3.scaleLinear().domain(xDomain).range([leftX, rightX]);

Then assuming we have an array of verticalPoints:

const verticalPoints: number[] = [];

we just add values in the xDomain like this:

verticalPoints.push(xScale(value))

and we can render our vertical lines on the x-axis with the CartesianGrid like this:

<CartesianGrid stroke="#d5d5d5" verticalPoints={verticalPoints} />