[TASK] bugfix chart if array length less than 2

This commit is contained in:
Marie Birner 2023-10-01 18:53:52 +02:00
parent dd7709ec3f
commit f92a913858

View File

@ -8,46 +8,48 @@ export interface Data {
if(sessionStorage.getItem('userStats')) { if(sessionStorage.getItem('userStats')) {
const data = JSON.parse(sessionStorage.getItem('userStats') || '{}') as Data[]; const data = JSON.parse(sessionStorage.getItem('userStats') || '{}') as Data[];
const margin = { top: 20, right: 20, bottom: 50, left: 50 }; if(data.length >= 2) {
const width: number = 960 - margin.left - margin.right; const margin = { top: 20, right: 20, bottom: 50, left: 50 };
const height: number = 500 - margin.top - margin.bottom; const width: number = 960 - margin.left - margin.right;
const height: number = 500 - margin.top - margin.bottom;
data.forEach((d: Data) => {
d.date = <Date> new Date(d.date) data.forEach((d: Data) => {
d.km = +d.km; d.date = <Date> new Date(d.date)
}); d.km = +d.km;
});
const x = d3.scaleTime()
.domain(<[Date, Date]>d3.extent(data, (d: Data) => d.date)) const x = d3.scaleTime()
.range([0, width]); .domain(<[Date, Date]>d3.extent(data, (d: Data) => d.date))
.range([0, width]);
const y = d3.scaleLinear()
.domain([0, Number(d3.max(data, (d: Data) => d.km))]) const y = d3.scaleLinear()
.range([height, 0]); .domain([0, Number(d3.max(data, (d: Data) => d.km))])
.range([height, 0]);
const line = d3.line<Data>()
.x((d: Data) => x(d.date)) const line = d3.line<Data>()
.y((d: Data) => y(d.km)); .x((d: Data) => x(d.date))
.y((d: Data) => y(d.km));
const svg = d3.select('#container')
.append('svg') const svg = d3.select('#container')
.attr('width', width + margin.left + margin.right) .append('svg')
.attr('height', height + margin.top + margin.bottom) .attr('width', width + margin.left + margin.right)
.call(responsivefy) .attr('height', height + margin.top + margin.bottom)
.append('g') .call(responsivefy)
.attr('transform', `translate(${margin.left},${margin.top})`); .append('g')
.attr('transform', `translate(${margin.left},${margin.top})`);
svg.append('path')
.data([data]) svg.append('path')
.attr('class', 'line') .data([data])
.attr('d', line); .attr('class', 'line')
.attr('d', line);
svg.append('g')
.attr('transform', `translate(0,${height})`) svg.append('g')
.call(d3.axisBottom(x)); .attr('transform', `translate(0,${height})`)
.call(d3.axisBottom(x));
svg.append('g')
.call(d3.axisLeft(y)); svg.append('g')
.call(d3.axisLeft(y));
}
} }