Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import React, { useEffect, useRef } from 'react';
import * as d3 from 'd3';
const BarChart = ({ data }) => {
const d3Chart = useRef();
const drawChart = () => {
const margin = { top: 50, right: 40, bottom: 70, left: 60 };
const width = 1000 - margin.left - margin.right;
const height = 500 - margin.top - margin.bottom;
d3.select(d3Chart.current).select("svg").remove();
const svg = d3.select(d3Chart.current)
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", `translate(${margin.left}, ${margin.top})`);
const x = d3.scaleBand()
.range([0, width])
.padding(0.1);
const y = d3.scaleLinear()
.range([height, 0]);
x.domain(data.map(d => d.date));
y.domain([0, d3.max(data, d => d.occurrences)]);
svg.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", "bar")
.attr("width", x.bandwidth())
.attr("x", d => x(d.date))
.attr("y", d => y(d.occurrences))
.attr("height", d => height - y(d.occurrences));
// Axe X
svg.append("g")
.attr("transform", `translate(0, ${height})`)
.call(d3.axisBottom(x))
.selectAll("text")
.attr("transform", "rotate(-45)")
.style("text-anchor", "end");
// axe Y
svg.append("g")
.call(d3.axisLeft(y));
// titre axe X
svg.append("text")
.attr("x", width / 2 )
.attr("y", height + margin.bottom - 20)
.style("text-anchor", "middle")
.text("Date");
// tiitre Axe Y
svg.append("text")
.attr("transform", `rotate(-90)`)
.attr("y", 0)
.attr("x",0 - (height / 2))
.attr("dy", "-1em")
.style("text-anchor", "middle")
.text("Nombre de ventes");
};
useEffect(() => {
if (data && data.length > 0) {
drawChart();
}
}, [data]);
return <div ref={d3Chart} />;
};
export default BarChart;