chart = {
const svg = d3.create("svg").attr("viewBox", [0,0,width,height]);
const x = d3.scaleLinear()
.domain([0, d3.max(chartData, d => d.average)])
.range([margin.left, width - margin.right]);
separated by a small gap.
*/
const y = d3.scaleBand()
.domain(chartData.map(d => d.name))
.rangeRound([margin.top, height - margin.bottom])
.padding(0.1);
/* Step 3: Draw the chart
https://observablehq.com/@d3/selection-join
*/
svg.selectAll("rect") //Selects all defined elements in the DOM and hands off a reference to the next step in the chain.
.data(chartData) //connect chart data with DOM <rect/> elements
.join("rect") // appends a new SVG rect element for each element in our chartdata array.
.attr('x', (d) => x(0)) //since this is a horizontal bar chart we start the bottom of the chart at the left
.attr('y', (d) => y(d.name)) // bar y position
.attr("height", y.bandwidth()) // height of the bar so they all stack nicely near eachother
.attr("width", (d) => x(d.average) - x(0)) // height of the bar so they all stack nicely near eachother
.attr("fill","green"); // color of the bar
/* Step 4: labeling */
//initialize the location for the X Axis
const xAxis = g => g
.attr("transform", `translate(0,${height - margin.bottom})`)
.call(d3.axisBottom(x))
// initialize the location of the Y axis
const yAxis = g => g
.attr("transform", `translate(${margin.left},0)`)
.call(d3.axisLeft(y))
// append each to the svg so they will be rendered
svg.append("g")
.call(xAxis)
// x-axis label
.call(g =>
g.select(".tick:last-of-type text").clone()
.attr("text-anchor", "middle")
.attr("x", -(width - margin.left - margin.right) / 2)
.attr("y", margin.bottom - 10)
.attr("font-weight", "bold")
.text("Average Price")
);
svg.append("g")
.call(yAxis)
// y-axis label
.call(g =>
g.select(".tick:last-of-type text").clone()
.attr("transform", `rotate(-90)`)
.attr("text-anchor", "middle")
.attr("x", (height/2) - margin.bottom - margin.top)
.attr("y", -margin.left + 20)
.attr("font-weight", "bold")
.text("Neighbourhood Group")
);
//return the svg for rendering in observable.
return svg.node();
}