Skip to content

Instantly share code, notes, and snippets.

@lnmunhoz
Last active March 16, 2019 05:23
Show Gist options
  • Save lnmunhoz/7837ebe34a972652977ec5622983c724 to your computer and use it in GitHub Desktop.
Save lnmunhoz/7837ebe34a972652977ec5622983c724 to your computer and use it in GitHub Desktop.
d3: revenues bar chart
license: mit
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
</style>
</head>
<body>
<script>
const profitData = [
{
"month": "January",
"revenue": "13432",
"profit": "8342"
},
{
"month": "February",
"revenue": "19342",
"profit": "10342"
},
{
"month": "March",
"revenue": "17443",
"profit": "15423"
},
{
"month": "April",
"revenue": "26342",
"profit": "18432"
},
{
"month": "May",
"revenue": "34213",
"profit": "29434"
},
{
"month": "June",
"revenue": "50321",
"profit": "45343"
},
{
"month": "July",
"revenue": "54273",
"profit": "47452"
}
].map(d => ({
...d,
profit: parseInt(d.profit)
}))
console.log(profitData)
const margin = {
left: 100,
right: 10,
top: 20,
bottom: 100
}
const width = 600 - margin.left - margin.right
const height = 400 - margin.top - margin.bottom
const svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", width + margin.top + margin.bottom)
const g = svg.append("g")
.attr("transform", `translate(${margin.left},${margin.top})`)
const x = d3.scaleBand()
.domain(profitData.map(d => d.month))
.range([0, width])
.paddingOuter(0.3)
.paddingInner(0.3)
const max = d3.max(profitData, d => d.revenue)
const y = d3.scaleLinear()
.domain([max, 0])
.range([0, height])
const xAxisCall = d3.axisBottom(x)
const yAxisCall = d3.axisLeft(y)
g.append("g")
.attr("transform", `translate(0, ${height})`)
.call(xAxisCall)
.selectAll("text")
.attr("text-anchor", `end`)
.attr("x", -5)
.attr("y", 10)
.attr("transform", `rotate(-40)`)
g.append("g")
.call(yAxisCall)
g.append("text")
.attr("y", height + 50)
.attr("x", width / 2)
.attr("font-size", "20px")
.attr("text-anchor", "middle")
.text("Month");
g.append("text")
.attr("y", -60)
.attr("x", -(height/2))
.attr("font-size", "20px")
.attr("text-anchor", "middle")
.attr("transform", "rotate(-90)")
.text("Revenue");
const rects = g.selectAll("rect").data(profitData)
rects.enter().append("rect")
.attr("x", (d, i) => x(d.month))
.attr("y", d => y(d.revenue))
.attr("width", x.bandwidth)
.attr("height", (d, i) => height - y(d.revenue))
.attr("fill", "gray")
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment