Estoy trabajando con ChartJS en un proyecto en este momento, mostrando registros agregados por el usuario para rastrear el peso, la frecuencia cardíaca, etc. Me encuentro con una excepción en la que si el usuario agrega 2 registros para 1 día que son valores ligeramente diferentes, obtengo este:
Donde puede ver, los ha agregado a ambos en el mismo eje. A continuación se muestra un ejemplo del conjunto de datos:
[ {x: '2021-09-21', y: '30.00'}, {x: '2021-09-22', y: '65.00'}, {x: '2021-09-23', y: '48.00'}, {x: '2021-09-23', y: '25.00'}, {x: '2021-09-24', y: '55.00'}, ]¿Hay algo incorporado con ChartJS que promedie esto o es un caso de implementarlo yo mismo mientras cargo los datos?
Gracias
Así que pensé que sería más fácil simplemente reducir la matriz yo mismo y proporcionar eso como el conjunto de datos para ChartJS, dejaré el código a continuación para cualquier persona en una posición similar. Hace uso de un gancho React para actualizar cada vez que se actualiza el conjunto de datos real:
/** * When the metric values have been updated */ useEffect(() => { /** * Init a new object to store the values in */ let sorted = {}; /** * Loop through all the metric values that were added */ metricValues.forEach((value) => { /** * If we already have a copy of it in the new object */ if (sorted[`${value.x}`]) { /** * Push the value onto the array */ sorted[`${value.x}`] = [...sorted[`${value.x}`], value.y]; } else { /** * Otherwise just set it as the first value */ sorted[`${value.x}`] = [value.y]; } }); /** * Init a new array to hold the reduced data */ let reducedData = []; /** * Loop through each of the now sorted values */ Object.entries(sorted).forEach((dataPoint) => { /** * Get the records array, holding the values to be averaged */ const dateRecords = dataPoint[1]; /** * Make a sum of all the records */ const recordsSum = dateRecords.reduce((a, b) => parseFloat(a) + parseFloat(b), 0); /** * Then find the avaerage */ const recordsAvg = parseFloat(recordsSum / dateRecords.length).toFixed(2); /** * Push this new reduced version of the metric records to our local array */ reducedData = [...reducedData, { x: `${dataPoint[0]}`, y: recordsAvg }]; }); /** * Push the complete reduced array into the local state */ setReducedMetricValues(reducedData); }, [metricValues]);