Cheatsheet
Cheatsheet
- HTML Structure:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>SVG and D3 Visualization</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div id="chart"></div>
</body>
</html>
```
- Event Handling:
```javascript
document.getElementById("chart").addEventListener("click", () => {
alert("Chart clicked!");
});
```
4. D3.js Basics
- Including D3.js:
```html
<script src="https://d3js.org/d3.v7.min.js"></script>
```
5. Data Binding in D3
- Basic Transition:
```javascript
svg.select("circle")
.transition()
.duration(1000)
.attr("r", 30);
```
- Chained Transitions:
```javascript
svg.select("circle")
.transition().duration(1000).attr("fill", "green")
.transition().duration(1000).attr("cx", 300);
```
- Staggered Transitions:
```javascript
svg.selectAll("circle")
.transition()
.delay((d, i) => i * 500)
.duration(1000)
.attr("cx", 400);
```
8. Bar Chart in D3
- Drawing Bars:```javascript
svg.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", "bar")
.attr("x", (d, i) => x(i))
.attr("y", d => y(d))
.attr("width", x.bandwidth())
.attr("height", d => height - y(d))
.attr("fill", "steelblue");
```
- Tooltip Setup:
```html
<div class="tooltip" style="position: absolute; display: none; background: #333; color: #fff;
padding: 5px; border-radius: 3px;"></div>
```
- Tooltip Code:
```javascript
const tooltip = d3.select(".tooltip");
svg.selectAll(".bar")
.on("mouseover", function(event, d) {
tooltip.style("display", "block")
.html(`Value: ${d}`)
.style("left", (event.pageX + 10) + "px")
.style("top", (event.pageY - 20) + "px");
d3.select(this).attr("stroke-width", 2).attr("stroke", "black");
})
.on("mouseout", function() {
tooltip.style("display", "none");
d3.select(this).attr("stroke-width", 1);
});
```
- Setting Up Scales:
```javascript
const x = d3.scaleLinear().domain([0, d3.max(data, d => d.x)]).range([0, width]);
const y = d3.scaleLinear().domain([0, d3.max(data, d => d.y)]).range([height, 0]);
```
- Drawing Points:
```javascript
svg.selectAll("circle")
.data(data)
.enter()
.append("circle")
.attr("cx", d => x(d.x))
.attr("cy", d => y(d.y))
.attr("r", 5)
.attr("fill", "steelblue");
```
- Adding Axes:
```javascript
svg.append("g").attr("transform", `translate(0,${height})`).call(d3.axisBottom(x));
svg.append("g").call(d3.axisLeft(y));
```