I started the D3.js challenge on FreeCodeCamp, the problem is that I solved it with the chart but it only gives me a display on the rectum, only one with the width and height that it I put, I’ll show the code below.
The entire code on
JavaScript
x
78
78
1
<script>
2
3
//set d3
4
var w = 1000, h = 500;
5
var padding = 50;
6
var svg = d3.select('body')
7
.append('svg')
8
.attr('width', w)
9
.attr('height', h)
10
11
//title
12
svg.append('text')
13
.attr('x', w / 2)
14
.attr('y', 50)
15
.text('United States GDP')
16
17
18
fetch('https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/GDP-data.json')
19
.then((result)=>result.json())
20
.then((data)=>{
21
22
var the_data = data['data']
23
24
//get vals
25
var get_max = d3.max(data['data'])
26
var get_mix = d3.min(data['data'])
27
28
//for x
29
var max_x = Number(get_max[0].split('-')[0])
30
var min_x = Number(get_mix[0].split('-')[0])
31
32
//for y
33
var max_y = get_max[1]
34
var min_y = get_mix[1]
35
36
37
var xScale = d3.scaleLinear()
38
.domain([min_x, max_x])
39
.range([padding, w-padding])
40
41
var yScale = d3.scaleLinear()
42
.domain([min_y, max_y])
43
.range([h-padding, padding])
44
45
46
//the_chars
47
for(var i in the_data){
48
var get_year = Number(the_data[i][0].split('-')[0])
49
the_data[i][0] = get_year
50
}
51
52
svg.selectAll('rect')
53
.data(the_data)
54
.enter()
55
.append('rect')
56
.attr("x", (d) => { xScale(d[0]) })
57
.attr('y', (d)=>{ yScale(d[1]) })
58
.attr("width", 200)
59
.attr("height", 20)
60
61
//axis
62
const xAxis = d3.axisBottom(xScale);
63
const yAxis = d3.axisLeft(yScale);
64
65
//display axis
66
svg.append("g")
67
.attr("transform", "translate(0," + (h - padding) + ")")
68
.call(xAxis);
69
70
svg.append('g')
71
.attr('transform', 'translate(' + padding + ', 0)')
72
.call(yAxis)
73
74
75
76
77
})
78
Now, what I need to do to display the charts!
I mention that the script tags are embedded in the body
Advertisement
Answer
- Problem: Arrow functions without a return value. Solution: Instead use an explicit or an implicit return.
JavaScript
1
4
1
.attr("x", (d) => { xScale(d[0]) }) // returns undefined
2
.attr("x", (d) => xScale(d[0])) // implicit return
3
.attr("x", (d) => { return xScale(d[0]) }) // explicit return
4
- Problem: Fixed height value. Solution Evaluate the height of each based on the GDP value (
d[1]
) instead.
JavaScript
1
5
1
.attr('height', 20) // fixed height
2
.attr('height', d => yScale(min_y) - yScale(d[1]))
3
// subtract from min range to account for padding and inverted y coordinates in SVG
4
5
Full solution in this codepen