Added solution to D3: Add axes challenge (#34243)
* Update index.md * Update index.md
This commit is contained in:
committed by
Christopher McCormack
parent
df3a4db5ba
commit
f991a487a1
@ -3,8 +3,77 @@ title: Add Axes to a Visualization
|
||||
---
|
||||
## Add Axes to a Visualization
|
||||
|
||||
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/data-visualization/data-visualization-with-d3/add-axes-to-a-visualization/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
|
||||
### Hint 1
|
||||
|
||||
<a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
|
||||
Set the y-axis variable using `const yAxis = d3.axisLeft(yScale);`.
|
||||
|
||||
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
|
||||
### Hint 2
|
||||
|
||||
Append the y-axis using `svg.append()`.
|
||||
|
||||
### Spoiler Alert | Solution Ahead
|
||||
### Solution
|
||||
|
||||
To solve the challenge, use:
|
||||
```html
|
||||
<body>
|
||||
<script>
|
||||
const dataset = [
|
||||
[ 34, 78 ],
|
||||
[ 109, 280 ],
|
||||
[ 310, 120 ],
|
||||
[ 79, 411 ],
|
||||
[ 420, 220 ],
|
||||
[ 233, 145 ],
|
||||
[ 333, 96 ],
|
||||
[ 222, 333 ],
|
||||
[ 78, 320 ],
|
||||
[ 21, 123 ]
|
||||
];
|
||||
|
||||
const w = 500;
|
||||
const h = 500;
|
||||
const padding = 60;
|
||||
|
||||
const xScale = d3.scaleLinear()
|
||||
.domain([0, d3.max(dataset, (d) => d[0])])
|
||||
.range([padding, w - padding]);
|
||||
|
||||
const yScale = d3.scaleLinear()
|
||||
.domain([0, d3.max(dataset, (d) => d[1])])
|
||||
.range([h - padding, padding]);
|
||||
|
||||
const svg = d3.select("body")
|
||||
.append("svg")
|
||||
.attr("width", w)
|
||||
.attr("height", h);
|
||||
|
||||
svg.selectAll("circle")
|
||||
.data(dataset)
|
||||
.enter()
|
||||
.append("circle")
|
||||
.attr("cx", (d) => xScale(d[0]))
|
||||
.attr("cy",(d) => yScale(d[1]))
|
||||
.attr("r", (d) => 5);
|
||||
|
||||
svg.selectAll("text")
|
||||
.data(dataset)
|
||||
.enter()
|
||||
.append("text")
|
||||
.text((d) => (d[0] + "," + d[1]))
|
||||
.attr("x", (d) => xScale(d[0] + 10))
|
||||
.attr("y", (d) => yScale(d[1]))
|
||||
|
||||
const xAxis = d3.axisBottom(xScale);
|
||||
const yAxis = d3.axisLeft(yScale);
|
||||
|
||||
svg.append("g")
|
||||
.attr("transform", "translate(0," + (h - padding) + ")")
|
||||
.call(xAxis);
|
||||
|
||||
svg.append("g")
|
||||
.attr("transform", "translate(" + padding + ", 0)")
|
||||
.call(yAxis);
|
||||
</script>
|
||||
</body>
|
||||
```
|
||||
|
Reference in New Issue
Block a user