Skip to content

Instantly share code, notes, and snippets.

@tomshanley
Last active February 3, 2020 00:19
Show Gist options
  • Save tomshanley/4d3e3727fd4172091765ca1d62d21517 to your computer and use it in GitHub Desktop.
Save tomshanley/4d3e3727fd4172091765ca1d62d21517 to your computer and use it in GitHub Desktop.
fresh block
license: mit
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
svg { display: block }
</style>
</head>
<body>
<script>
console.clear()
let pData = [
{"name": "p", "threshold": 0, "cost": 7.5},
{"name": "p", "name": "pgg", "threshold": 25, "cost": 15},
{"name": "p", "threshold": 50, "cost": 50},
{"name": "p", "threshold": 100, "cost": 100}
]
let fData = [
{"name": "f", "threshold": 0, "cost": 10},
{"name": "f", "threshold": 20, "cost": 15},
{"name": "f", "threshold": 40, "cost": 50},
{"name": "f", "threshold": 100, "cost": 100}
]
let width = 500
let height = 220
let margin = 40
let upperThreshold = 300
let colour = d3.scaleOrdinal()
.domain(["pgg", "fs"])
.range(["blue", "green"])
let xScale = d3.scaleLinear()
.domain([0, upperThreshold])
.range([0, width])
let yScale = d3.scaleLinear()
.domain([0, 150])
.range([height, 0])
let xAxis = d3.axisBottom(xScale)
let yAxis = d3.axisLeft(yScale)
.ticks(15)
let rectsData = []
rectsData.push([])
rectsData.push([])
function createRectData(data, index) {
data.forEach(function(d, i){
let obj = {}
obj.name = d.name
obj.lower = xScale(d.threshold)
obj.upper = i == data.length - 1 ? xScale(upperThreshold) : xScale(data[i+1].threshold)
obj.width = obj.upper - obj.lower
obj.y = yScale(d.cost)
obj.height = height - obj.y
obj.cost = d.cost
rectsData[index].push(obj)
})
}
createRectData(pData, 0)
createRectData(fData, 1)
let companies = d3.select("body").selectAll("svg")
.data(rectsData)
.enter()
.append("div")
companies.append("h1")
.text(d => d[0].name)
let svg = companies.append("svg")
.attr("width", width + margin + margin)
.attr("height", height + margin + margin)
.append("g")
.attr("transform", "translate(" + margin + "," + margin + ")")
let axes = svg.append("g")
let x = axes.append("g")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
let y = axes.append("g")
.call(yAxis)
axes.selectAll(".domain").remove()
y.selectAll(".tick").selectAll("line")
.attr("x1", width)
.style("opacity", 0.3)
y.selectAll("text")
.text(d => formatCost(d))
x.selectAll("text")
.text(d => formatWeight(d))
let rects = svg.selectAll(".rect")
.data(d => d)
.enter()
.append("g")
rects.append("rect")
.attr("x", d => d.lower)
.attr("y", d => d.y)
.attr("width", d => d.width)
.attr("height", d => d.height)
.style("fill", d => colour(d.name))
.style("fill-opacity", 0.3)
.style("stroke", d => colour(d.name))
.style("stroke-width", 2)
function formatCost(c){
return "$"+c
}
function formatWeight(w){
return w + "kg"
}
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment