Get the Y value for a given X value
See original GitHub issueWhat is the problem?
Hope Iām not being too active on these issues right now š¤ This is more like an idea / feature: Getting the Y value for a given X value. When the XAxis is linear (e.g time), it would be nice to have a function like x()
and y()
but not for the coordinates, but for the values. For example, if you have the following input:
[
{ value: 10, timestamp: new Date(2018, 06, 25) },
// One day missing
{ value: 20, timestamp: new Date(2018, 06, 27) }
]
The graph is now going to be painted as if the values were like so:
[
{ value: 10, timestamp: new Date(2018, 06, 25) },
{ value: 15, timestamp: new Date(2018, 06, 26) },
{ value: 20, timestamp: new Date(2018, 06, 27) }
]
So, by providing the x
value, in this case time, it should be possible to find out not only what coordinate the graph has plotted the Y value on, but what the Y value actually is ā by providing yValueForX(new Date(2018, 06, 26))
we should be able to get 15
back, as thatās already plotted on the graph?
TL;DR: It should be possible to retrieve the āin-betweenā values, given an X-value within the domain for the graph
Issue Analytics
- State:
- Created 5 years ago
- Reactions:3
- Comments:9 (2 by maintainers)
Top GitHub Comments
I hear you. Iāll have to look into if d3.js have that option anywhere, since thatās what Iām using to generate the paths.
For anyone having this issue, hereās my solution:
Step I: Get the SVG String
First, I bring the SVG string generated internally by
area-chart.js
into my React componentās state. I do this by mounting this extractor component as a child of the chart:The
line
prop comes fromchart.js
, which passesextraProps
to all chart child components. You could also use this prop directly if youāre building a child component.Step II: Iterate the SVG to find the Y Value
Next, I get the Y value from the extracted SVG. To do that, I found a browser script which uses binary search (instead of the bisect function): https://www.freecodecamp.org/news/how-to-build-react-native-charts-with-dynamic-tooltips-64aefc550c95/
Unfortunately, this script requires the
getPointAtLength
, andgetTotalLength
browser API functions. After some research, I found a pure JS alternative calledsvg-path-properties
: https://www.npmjs.com/package/svg-path-propertiesThe final script to calculate the Y-Value in React Native then looks like this:
Within my React component, I get the Y-Value with:
It should also possible to do this with bisect by first iterating through the SVG and creating an array of values in the x domain.
Itās a little messy but it works for now =)