D3库没有正确转换值(React Native)



我有一个显示时间持续时间的条形图,但是,条形图显示不准确。例如:总时长为1h 05m,等于1.0757。当我对总持续时间:d3.scaleLinear().range([0,height]).domain([min,max])调用d3函数时,它返回值31.8486,使条形图看起来像是描绘30分钟vs超过一个小时。

需要切换什么以确保条形图正确显示数据?

let h = 200;
let y = this.getDomainAndRange(data, h);
let displayOrder = [
0: {dayName: "Sunday", totalDuration: {value: 2.6707, display: "2h 40m"},
1: {dayName: "Monday", totalDuration: {value: 1.0757, display: "1h 5m"},
2: {dayName: "Tuesday", totalDuration: {value: 1.562, display: "1h 34m"}
]
// Once d3 is called on the totalDuration[value], it returns:
// 0: 200 (appears on the screen as 3h), 
// 1: 31.8486 (appears on the screen as 30m),
// 2: 83.116335 (appears on the screen as 1h 10m)
<Svg>
displayOrder.map((wd, idx) => {
let barHeight = this.getDayDurationHeight(data, wd, y);
let actualDuration = this.getActualDuration(data, wd)
return (
<G key={data["start"] + "g_" + idx}>
<Rect key={data["start"] + "wdb_" + idx} id={actualDuration} x={(idx + 1) * 45} width={bw} y={h - barHeight} height={barHeight} fill={purple} />
</G>
);
})
</Svg>
getDomainAndRange(data, height) {
//iterate through each day and find the min and max value...
let days = data["days"];
let min = Number.MAX_SAFE_INTEGER;
let max = Number.MIN_SAFE_INTEGER;
for (let i = 0; i < days.length; i++) {
let day = days[i];
if (day["totalDuration"]["value"] > max) max = day["totalDuration"]["value"];
if (day["totalDuration"]["value"] < min) min = day["totalDuration"]["value"];
}
if (max <= 0) max = 1;
let x = d3.scaleLinear().range([0, height]).domain([min, max])
return x;
}
getDayDurationHeight(data, dayName, dr) {
//iterate through each day and find the bar height value...
let days = data["days"];
let duration = dr(0);
for (let i = 0; i < days.length; i++) {
let day = days[i];
if (day["dayName"] == dayName) {
//this is where the d3 function is converting the value
duration = dr(day["totalDuration"]["value"]);
}
}
return duration;
}
getActualDuration(data, dayName){
let days = data["days"];
let duration = 0
for (let i = 0; i < days.length; i++) {
let day = days[i];
if (day["dayName"] == dayName) {
duration = (day["totalDuration"]["display"]);
}
}
return duration;
}

解决方案如下:

if (day["totalDuration"]["value"] > max) max = day["totalDuration"]["value"];

需要切换到

if (day["totalDuration"]["value"] > max) max = Math.ceil(day["totalDuration"]["value"]);

同时,d3函数中的min需要设置为0

original:let x = d3.scaleLinear().range([0, height]).domain([min, max])

修正:let x = d3.scaleLinear().range([0, height]).domain([0, max])

原因:顶部行被设置为max,这是当前行的确切编号。添加Math.ceil()后,顶行将变为整数。此外,底线正在上升到min。相反,它应该始终是0,而不是根据min切换。

最新更新