Create a gist now

Instantly share code, notes, and snippets.

@shimizu /.block
Last active Oct 26, 2017

What would you like to do?
Inversion with ordinal scale
license: mit

Ordiran scaleにinvertメソッドがなかったので、代価案を考えた。

Built with

<!DOCTYPE html>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<title>D3 ver.4 - ordinal scale invert</title>
html, body {
width: 100%;
height: 100%;
padding: 0px;
margin: 0px;
svg {
width: 900px;
<svg id="example"></svg>
<script src="//"></script>
var width = document.querySelector("svg").clientWidth
var height = document.querySelector("svg").clientHeight
var margin = {top:50, left:50, bottom:50, right:50 }
var svg ="#example")
var AxisLayer = svg.append("g").attr("class", "AxisLayer")
var chartLayer = svg.append("g").attr("class", "chartLayer")
.attr("transform", "translate("+[margin.left,]+")")
var overLayer = svg.append("g").attr("class", "overLayer")
.attr("transform", "translate("+[margin.left,]+")")
var guideLine = overLayer.append("line")
.attr("class", "guideLine")
.attr("x1", 0)
.attr("y1", 0)
.attr("x2", 0)
.attr("y2", height-(
.attr("stroke", "red")
var eventCapture = chartLayer.append("rect")
.attr("width", width-(margin.left+margin.right))
.attr("height", height-(
.attr("opacity", 0)
var xScale = d3.scaleBand()
var yScale = d3.scaleLinear()
var xAxis = d3.axisBottom()
var yAxis = d3.axisLeft()
xScale.domain(["A", "B", "C", "D", "E", "F", "G", "H"]).range([0, width-(])
yScale.domain([0, 1000]).range([height-(, 0])
// custom invert function
xScale.invert = (function(){
var domain = xScale.domain()
var range = xScale.range()
var scale = d3.scaleQuantize().domain(range).range(domain)
return function(x){
return scale(x)
.on("mousemove", function(e){
var xy = d3.mouse(eventCapture.node())
var d = xScale.invert(xy[0])
var nx = xScale(d) + (xScale.bandwidth()/2)
guideLine.transition().duration(100).attr("x1", nx).attr("x2", nx)
function drawAxis(){
var t = d3.transition()
var x = AxisLayer.selectAll(".x")
var newX = x.enter().append("g")
.attr("class", "x axis")
.attr("transform", "translate("+[margin.left,]+")")
var y = AxisLayer.selectAll(".y")
var newY = y.enter().append("g")
.attr("class", "y axis")
.attr("transform", "translate("+[margin.left,]+")")

This comment has been minimized.

Show comment Hide comment

PedroF20 Oct 26, 2017

Wow, this is a very good solution, thank you!

Wow, this is a very good solution, thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment