palerdot / react-d3-speedometer

React Speedometer component using d3.js ⚛️
https://palerdot.in/react-d3-speedometer/
MIT License
230 stars 57 forks source link

Custom segment labels display error #183

Closed shiwofeiwo closed 6 months ago

shiwofeiwo commented 6 months ago

When i set value=200, minValue=100, maxValue=500, customSegmentLabels=[ { "text": "1", "position": "OUTSIDE", "fontSize": "14px", "color": "#783535" }, { "text": "2", "position": "OUTSIDE", "fontSize": "14px", "color": "#000000" }, { "text": "3", "position": "OUTSIDE", "fontSize": "14px", "color": "#9013fe" }, { "text": "4", "position": "OUTSIDE", "fontSize": "14px", "color": "#8b572a" }, { "text": "5", "position": "OUTSIDE", "fontSize": "14px", "color": "#7ed321" } ] then the last label named "5" display in wrong position image image

palerdot commented 6 months ago

You have to change your min value to 0. This is because the total number of segments is decided by d3-ticks and it has to match the custom segment labels you are providing. In your case, when you give a minValue={100}, the end result will be 4 segments (100-200, 200-300, 300-400, 400-500) and not 5 segments like you think when you pass an array of 5 values to your customSegmentLabels. For more details check https://d3js.org/d3-array/ticks

From the documentation

Please note, segments is calculated with [d3-ticks](https://github.com/palerdot/react-d3-speedometer/blob/master) which is an approximate count that is uniformly spaced between min and max. Please refer to [d3-ticks](https://github.com/d3/d3-scale/blob/master/README.md#continuous_ticks) and [d3-array ticks](https://github.com/d3/d3-array#ticks) for more detailed info.

Also please refer d3 documentation - https://d3js.org/d3-array/ticks, and play around with a min and max values.

palerdot commented 6 months ago

Explaining the technical part here for future reference. Please refer to https://d3js.org/d3-array/ticks for details

// 100 => minValue, 500 => maxValue, 5 => your preferred segments
d3.ticks(100, 500, 5)
// you will get
[ 100, 200, 300, 400, 500 ] => 4 segments
// this is 4 segments
100-200, 200-300, 300-400,400-500

For you preferred customSegmentLabels length of 5, you should actually get back an array of 6 values (which you will get if you set your minValue to 0). 6 values => 5 segments. customSegmentLabels is just custom text for your calculated segments. Your segments should match the customSegmentLabels

shiwofeiwo commented 6 months ago

Thanks for explaining.