Blog>
Snippets

Integrating Statistical Analysis Outputs into React Charts

Illustrate how to take the output from a statistical analysis library, like Simple Statistics, and visualize the results (e.g., mean, median) on a TanStack React Chart.
import { useMemo } from 'react';
import { Chart } from 'tanstack-react-charts';
import * as ss from 'simple-statistics';
Imports React, TanStack React Charts, and Simple Statistics library.
const data = useMemo(() => [
  { x: 'Dataset 1', y: 10 },
  { x: 'Dataset 2', y: 20 },
  { x: 'Dataset 3', y: 5 },
  // Add your actual dataset here
], []);
Defines a sample dataset using the useMemo hook for performance optimization.
const processedData = useMemo(() => {
  const values = data.map(d => d.y);
  return [
    { x: 'Mean', y: ss.mean(values) },
    { x: 'Median', y: ss.median(values) },
    // Calculate other statistical measures as needed
  ];
}, [data]);
Processes the dataset to calculate statistical measures (mean, median) using Simple Statistics.
const axes = useMemo(() => [{
  primary: true,
  position: 'bottom',
  type: 'ordinal',
}, {
  position: 'left',
  type: 'linear',
}], []);
Configures the chart axes.
const series = useMemo(() => ({ type: 'bar' }), []);
Defines the chart to be a bar chart.
<Chart options={{
  data: processedData,
  axes,
  series,
}} />
Renders the chart with processed statistical data.