I am making a bar chart with the years on the X axis. Currently trying to remove the commas using, tickFormat()
but it throws an error.
JavaScript
x
2
1
Uncaught (in promise) TypeError: svg.append( ).attr( ).attr( ).classed( ).call( ).tickFormat is not a function at
2
Does anyone know what is wrong? My code:
JavaScript
1
30
30
1
let dataNumsOnly = [];
2
let labels = [];
3
4
fetch('https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/GDP-data.json')
5
.then(response => response.json())
6
.then(data => {
7
let dataForChart = data;
8
dataForChart = dataForChart.data;
9
for (let i = 0; i < dataForChart.length; i++) { //grabs data and labels.
10
dataNumsOnly.push(dataForChart[i][1]);
11
labels.push(dataForChart[i][0]);
12
}
13
14
let svg = d3.select('body')
15
.append('svg')
16
.attr('width', 1060.4)
17
.attr('height', 690);
18
19
const xScale = d3.scaleLinear()
20
.domain([1947, 2015])
21
.range([0, 961]);
22
23
svg.append('g')
24
.attr('transform', 'translate(50, 638)')
25
.attr('id', 'x-axis')
26
.classed('tick', true)
27
.call(d3.axisBottom(xScale))
28
.tickFormat(d3.format("d"))
29
});
30
Advertisement
Answer
Turns out I had to nest it inside the call
for the axis.
JavaScript
1
65
65
1
let dataNumsOnly = [];
2
let labels = [];
3
4
fetch('https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/GDP-data.json')
5
.then(response => response.json())
6
.then(data => {
7
let dataForChart = data;
8
dataForChart = dataForChart.data;
9
for (let i = 0; i < dataForChart.length; i++) { //grabs data and labels.
10
dataNumsOnly.push(dataForChart[i][1]);
11
labels.push(dataForChart[i][0]);
12
}
13
14
const svg = d3.select('body')
15
.append('svg')
16
.attr('width', 1060.4)
17
.attr('height', 690);
18
console.log(dataNumsOnly)
19
svg.selectAll('rect')
20
.data(dataNumsOnly)
21
.enter()
22
.append('rect')
23
.classed('bar', true)
24
.attr('width', 3)
25
.attr('height', d => d / 32)
26
.attr("x", (d, i) => i * 3.5)
27
.attr('transform', 'translate(50, 38.4)')
28
.attr('y', d => 600 - d / 32)
29
.style('fill', "#8abccf");
30
31
svg.append('text')
32
.attr('transform', 'translate(420, 50)')
33
.classed('info', true)
34
.text('More Information: http://www.bea.gov/national/pdf/nipaguid.pdf');
35
36
svg.append('text')
37
.classed('info', true)
38
.attr('transform', 'rotate(-90)')
39
.attr('x', -420)
40
.attr('y', 90)
41
.text('Gross Domestic Product');
42
43
const yScale = d3.scaleLinear()
44
.domain([0, 20000])
45
.range([600, 0]);
46
47
svg.append('g')
48
.attr('transform', 'translate(50, 38)')
49
.classed('tick', true)
50
.attr('id', 'y-axis')
51
.call(d3.axisLeft(yScale)
52
.ticks(10));
53
54
const xScale = d3.scaleLinear()
55
.domain([1947, 2015])
56
.range([0, 961]);
57
58
svg.append('g')
59
.attr('transform', 'translate(50, 638)')
60
.attr('id', 'x-axis')
61
.classed('tick', true)
62
.call(d3.axisBottom(xScale)
63
.tickFormat(d3.format('d')));
64
});
65