Last active
February 21, 2017 13:32
-
-
Save basilesimon/46a26c8bbcd18b384591301f27023893 to your computer and use it in GitHub Desktop.
simple scale with marker
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<head> | |
<meta charset="utf-8"> | |
<script src="https://d3js.org/d3.v4.min.js"></script> | |
<style> | |
body { margin: 10; padding: 10;position:fixed;top:0;right:0;bottom:0;left:0; } | |
svg { margin: 10; padding: 10} | |
path { display: none; } | |
</style> | |
</head> | |
<body> | |
<script> | |
// visits is our data point | |
// its value is from -1 to 1 | |
var visits = .5, | |
chunks = [-1, -.5, 0, .5, 1], | |
ticks = [-1, 0, 1], | |
tickLabels = ['a','b','c'] | |
width = 300, | |
height = 50; | |
// Feel free to change or delete any of the code you see in this editor! | |
var svg = d3.select("body").append("svg") | |
.attr("width", width) | |
.attr("height", 500); | |
var threshold = d3.scaleThreshold() | |
.domain([-0.6, -0.2, 0.2, 0.6, 1]) | |
.range(["#d7191c", "#fdae61", "#ffffbf", "#a6d96a", "#1a9641"]); | |
var x = d3.scaleLinear().range([0, width]).domain([-1, 1]); | |
// remove if unnecessary | |
var xAxis = d3.axisBottom() | |
.scale(x); | |
// remove if unnecessary | |
svg.append("g") | |
.attr("class", "x axis") | |
.attr("transform", "translate(0," + height + ")") | |
.call(xAxis | |
.ticks(3) | |
.tickValues(ticks) | |
.tickFormat(function(d,i){ return tickLabels[i] })) | |
.append("text") | |
.attr("class", "label") | |
.attr("transform", "translate(" + width + ",0)") | |
.attr("y", -5) | |
svg.selectAll("rect") | |
.data(threshold.range().map(function(color) { | |
var d = threshold.invertExtent(color); | |
if (d[0] == null) d[0] = x.domain()[0]; | |
if (d[1] == null) d[1] = x.domain()[1]; | |
return d; | |
})) | |
.enter().append("rect") | |
.attr("height", 20) | |
.attr("x", function(d) { return x(d[0]); }) | |
.attr("y", height-20) | |
.attr("width", function(d) { return x(d[1]) - x(d[0]); }) | |
.attr("fill", function(d) { return threshold(d[0]); }); | |
// marker | |
svg.append("g").append("text") | |
.text("#") | |
.attr("dx", x(visits)) | |
.attr("dy", height-20); | |
</script> | |
</body> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment