<svg id="chart"></svg>
const data = [
{
name: "Banana Production",
value: 20223290811
},
{
name: "Apple Production",
value: 8191091088.532
},
{
name: "Clementine Production",
value: 1162341399.19
}
];
const margin = { top: 20, right: 20, bottom: 70, left: 90 };
const width = 600 - margin.left - margin.right;
const height = 300 - margin.top - margin.bottom;
const svg = d3
.select("#chart")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom);
const xValues = [];
data.map(datum => xValues.push(datum.name));
const xScale = d3
.scaleBand()
.domain(xValues)
.range([0, width])
.padding(0.1);
const yValues = [];
data.map(datum => yValues.push(datum.value));
const yScale = d3
.scaleLinear()
.domain([0, d3.max(yValues)])
.range([height, 0]);
const barGroups = svg
.append("g")
.attr("class", "data")
.attr("transform", `translate(${margin.left}, 0)`);
barGroups
.selectAll("rect")
.data(data)
.enter()
.append("rect")
.attr("fill", "#d35f5f")
.attr("x", d => xScale(d.name))
.attr("y", d => yScale(d.value))
.attr("width", xScale.bandwidth())
.attr("height", d => height - yScale(d.value));
const xAxis = d3.axisBottom(xScale).tickSize(0);
svg
.append("g")
.attr("class", "x-axis")
.attr("transform", `translate(${margin.left}, ${height})`)
.call(xAxis);
d3.selectAll(".tick")
.append("text")
.text((d, i) =>
d3
.format(".2s")(data[i].value)
.replace("G", "B")
);
const increment = Math.ceil(d3.max(yValues) / 5);
const tickRange = d3.range(0, d3.max(yValues), increment);
var yAxis = d3
.axisLeft(yScale)
.tickValues(tickRange)
.tickFormat(d =>
d3
.format(".2s")(d)
.replace("G", "B")
);
svg
.append("g")
.attr("class", "y-axis")
.attr("transform", `translate(${margin.left}, 0)`)
.call(yAxis);
This Pen doesn't use any external CSS resources.