Plot.jsx 2.01 KB
Newer Older
Florent Chehab's avatar
Florent Chehab committed
1
import React from "react";
2
import { Line } from "react-chartjs-2";
Florent Chehab's avatar
Florent Chehab committed
3
import PropTypes from "prop-types";
4

5
6
7
8
9
10
11
12
13
14
const colors = [
  "#1f77b4",
  "#ff7f0e",
  "#2ca02c",
  "#d62728",
  "#9467bd",
  "#8c564b",
  "#e377c2",
  "#7f7f7f",
  "#bcbd22",
Florent Chehab's avatar
Florent Chehab committed
15
  "#17becf",
16
];
17

18
function PlotResult({ result }) {
19
20
21
22
23
24
  if (
    !Object.keys(result[0]).includes("x") ||
    !Object.keys(result[0]).includes("y")
  ) {
    return (
      <div>
Florent Chehab's avatar
Florent Chehab committed
25
        <br />
26
27
28
        Pour afficher les résultats sous forme graphique, vous devez préciser
        'x' et 'y' dans le SELECT (pensez à utiliser un ORDER BY sur X). Vous
        pouvez également préciser des catégories avec 'cat'.
Florent Chehab's avatar
Florent Chehab committed
29
        <br />
30
31
32
      </div>
    );
  }
33
34

  if (!Object.keys(result[0]).includes("cat")) {
Florent Chehab's avatar
Florent Chehab committed
35
36
37
38
39
40
41
42
    const mapping = new Map();
    result.forEach(({ x, y }) => {
      mapping.set(x, y);
    });

    const X = [...mapping.keys()];
    X.sort();

43
44
45
46
    return (
      <div>
        <Line
          data={{
Florent Chehab's avatar
Florent Chehab committed
47
            labels: X,
48
49
50
51
52
            datasets: [
              {
                label: "y = f(x)",
                backgroundColor: "rgb(255, 99, 132)",
                borderColor: "rgb(255, 99, 132)",
Florent Chehab's avatar
Florent Chehab committed
53
54
55
                data: X.map((x) => mapping.get(x)),
              },
            ],
56
57
58
59
60
61
          }}
        />
      </div>
    );
  }

Florent Chehab's avatar
Florent Chehab committed
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
  const categories = [...new Set(result.map((el) => el.cat))];

  const mapping = new Map();
  result.forEach(({ x, y, cat }) => {
    if (!mapping.has(x)) {
      mapping.set(x, new Map());
    }

    mapping.get(x).set(cat, y);
  });

  const X = [...mapping.keys()];
  X.sort();

  const datasets = categories.map((cat, index) => ({
    label: cat,
78
79
    fill: "disabled",
    borderColor: colors[index % colors.length],
Florent Chehab's avatar
Florent Chehab committed
80
81
82
83
    data: X.map((x) => {
      const val = mapping.get(x).get(cat);
      return typeof val !== "undefined" ? val : 0;
    }),
84
85
  }));

86
87
88
89
  return (
    <div>
      <Line
        data={{
Florent Chehab's avatar
Florent Chehab committed
90
91
          labels: X,
          datasets,
92
93
94
95
96
97
        }}
      />
    </div>
  );
}

Florent Chehab's avatar
Florent Chehab committed
98
99
100
101
PlotResult.propTypes = {
  result: PropTypes.array.isRequired,
};

102
export default PlotResult;