Published
Edited
Apr 17, 2020
Insert cell
md`# Bar Chart From Scratch`
Insert cell
chart = {
var svg = d3.create("svg")
.attr("viewBox", [0, 0, width, height]);
svg.append("g")
.attr("transform", `translate(0,${height - margin.bottom})`)
.style("color", "steelblue")
.attr("font-size", "100")
.call(d3.axisBottom(x).tickSize(3))
svg.append("g")
.attr("transform", `translate(${margin.left},0)`)
.attr("class", "y-grid")
.style("color", "steelblue")
.call(d3.axisLeft(y).ticks(4).tickSize(-width))
.attr("opacity", "1")
svg.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("fill", "#dddd12")
.attr("class", "bar")
.attr("x", function(d) { return x(d.country); })
.attr("width", x.bandwidth())
.attr("y", function(d) { return y(d.pci); })
.attr("height", function(d) { return height-margin.bottom - y(d.pci); });
return svg.node();
}
Insert cell
data=d3.csvParse(await FileAttachment("bar-chart.csv").text(), d3.autoType)
Insert cell
barColor="#fcc603"
Insert cell
d3=require('d3@5')
Insert cell
margin = ({top: 40, right: 20, bottom: 30, left: 50})
Insert cell
width = 900
Insert cell
height= 250
Insert cell
x=d3.scaleBand().range([margin.left, width - margin.right]).padding(0.4)
.domain(data.map(function(d) { return d.country }))
Insert cell
y=d3.scaleLinear()
.domain([0, d3.max(data, function(d) { return d.pci })])
.range([height - margin.bottom , margin.top])
Insert cell
styles = html`
<style>
svg{
background-color:#111;
}
.tick-major{
fill:#f00
}
</style>
`
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more