Skip to content

Instantly share code, notes, and snippets.

@romsson
Last active January 25, 2019 05:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save romsson/1a0c14ecfd3f4a8eae6b7dc0140a5ada to your computer and use it in GitHub Desktop.
Save romsson/1a0c14ecfd3f4a8eae6b7dc0140a5ada to your computer and use it in GitHub Desktop.
bar chart axis color scale
license: mit
We can make this file beautiful and searchable if this error is corrected: No commas found in this CSV file in line 0.
value
1
2
5
6
10
<!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>
// 1. Create the SVG
var svg = d3.select("body")
.append("svg")
.attr("width", 800)
.attr("height", 600)
// 2. Generate data
var data = d3.range(33)
d3.csv('dataset.csv', function(error, raw) {
// Data pre-processing
raw.forEach(function(d, i) {
d.value = +d.value;
})
console.log(raw)
data = raw
});
// Axis
var x = d3.scaleBand()
.domain(data)
.paddingInner(0.05)
.range([0, 500])
var y = d3.scaleLinear()
.domain([d3.min(data), d3.max(data)])
.range([0, 100])
var xAxis = d3.axisBottom()
.scale(x);
// Line generator
var line = d3.line().curve(d3.curveCardinal)
.x(function(d, i) { return x(i); })
.y(function(d) { return 300 -y(d); })
svg.selectAll(".line").data([data]).enter()
.append("path")
.attr("class", "line")
.attr("d", function(d) { return line(d); })
.attr("stroke", "black")
svg.append('g')
.attr('transform', 'translate(15,' + 300 + ')')
.attr('class', 'x axis')
.call(xAxis);
var color = d3.scaleOrdinal(d3.schemeCategory20)
// 3. Data binding
svg.selectAll("rect").data(data).enter()
.append("rect")
.attr("x", function(d, i) { return x(d); })
.attr("y", function(d, i) { return 300 - y(d); })
.attr("width", function(d, i) { return x.bandwidth(); })
.attr("height", function(d, i) { return y(d); })
.attr("fill", function(d, i) { return color(i); })
.on("mouseover", function(d, i) {
d3.select(this).attr("fill", "red")
svg.append("text")
.attr("id", "label_" + d)
.attr("x", x(d))
.attr("y", 300 - y(d))
.text(d)
})
.on("mouseleave", function(d, i) {
d3.select(this).attr("fill", "green")
d3.selectAll("#label_" + d).remove()
})
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment