I have basic bar chart which is working in observablehq. Now trying to add the cells to my existing code does not seems to work. Any help on this ?
In my files:
HTML:
<script src="https://d3js.org/d3.v5.js"></script>
JS:
function drawBarChart() {
var data = analytics; // from another global var
var margin = ({ top: 20, right: 0, bottom: 30, left: 40 });
var height = 500;
var width = 600;
yAxis = g => g
.attr("transform", `translate(${margin.left},0)`)
.call(d3.axisLeft(y))
.call(g => g.select(".domain").remove())
xAxis = g => g
.attr("transform", `translate(0,${height - margin.bottom})`)
.call(d3.axisBottom(x).tickFormat(i => data[i].name).tickSizeOuter(0))
y = d3.scaleLinear()
.domain([0, d3.max(data, d => d.value)]).nice()
.range([height - margin.bottom, margin.top])
x = d3.scaleBand()
.domain(d3.range(data.length))
.range([margin.left, width - margin.right])
.padding(0.1)
const svg = d3.select("#graph")
.attr("viewBox", [0, 0, width, height]);
svg.append("g")
.attr("fill", "steelblue")
.selectAll("rect")
.data(data)
.join("rect")
.attr("x", (d, i) => x(i))
.attr("y", d => y(d.value))
.attr("height", d => y(0) - y(d.value))
.attr("width", x.bandwidth());
svg.append("g")
.call(xAxis);
svg.append("g")
.call(yAxis);
return svg.node();
}
Will there be less code if I did write my own d3.js code without observablehq ? I used this template because it fit exactly my need.
Thanks.