Here is the source of the data. Number of violent crimes in the United States in 2015
The code of this bar chart was inspired by this.
Built with blockbuilder.org
xxxxxxxxxx
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
body { margin:0
}
.label {
font-size: 16pt;
font-family: 'sans-serif';
alignment-baseline: middle;
fill: #ffffff;
}
.head {
font-size: 20pt;
font-family: 'Gill Sans MT';
alignment-baseline: middle;
fill: #890000;
}
.number, .subtitle {
font-size: 16pt;
font-family: 'sans-serif';
alignment-baseline: middle;
fill: #890000;
}
.bar {
fill: #ad0000;
}
</style>
</head>
<body>
<script>
const width = 960;
const height = 500
const margin = {
left: 50,
right: 180,
top: 100,
bottom: 100
}
const svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
svg.append('text')
.attr('class', 'head')
.attr('x', margin.left)
.attr('y', 85)
.text('Number of violent crimes in the United States in 2015');
const g = svg.append('g')
.attr('transform', `translate(${margin.left}, ${margin.top})`)
var data = [
{
name: "Total violent crimes",
value: 1197704
},
{
name: "Aggravated assult",
value: 764449
},
{
name: "Robbery",
value: 327374
},
{
name: "Rape",
value: 90185
},
{
name: "Murder",
value: 15696
}
]
const innerWidth = width - margin.left - margin.right;
const innerHeight = height - margin.top - margin.bottom;
const xValue = d => d.value;
const yValue = d => d.name;
const xScale = d3.scaleLinear()
.domain([0, d3.max(data, xValue)])
.range([0, innerWidth]);
const yScale = d3.scaleBand()
.domain(data.map(yValue).reverse())
.range([innerHeight, 0])
.padding(0.3);
const groups = g.selectAll('g').data(data);
const groupsEnter = groups
.enter().append('g')
.attr('transform', d => `translate(0, ${yScale(yValue(d))})`);
groupsEnter
.append('rect')
.attr('class', 'bar')
.attr('width', d => xScale(xValue(d)))
.attr('height', yScale.bandwidth())
.attr('fill', 'black');
groupsEnter
.append('text')
.attr('class', 'label')
.attr('x', 5)
.attr('y', yScale.bandwidth() / 2)
.text(function (d) {
if (d.name !== "Murder")
return d.name;
});
const percentFormat = d3.format(",.1%");
const xPercent = d => percentFormat(xValue(d) / xScale.domain()[1]);
groupsEnter
.append('text')
.attr('class', 'number')
.attr('x', d => xScale(xValue(d)) + 8)
.attr('y', yScale.bandwidth() / 2)
.text(function (d) {
if (d.name == "Murder") {
return 'Murder ' + `${xValue(d)} (${xPercent(d)})`;
} else {
return `${xValue(d)} (${xPercent(d)})`;
}
});
</script>
</body>
https://d3js.org/d3.v4.min.js