block by shimizu 61e5e06c2a9cc2cd9898694efb33f441

D3 Axis Tips#3 - Inner Tick Label

Full Screen

Axis Tips #3

Tick(ラベル)を内向きに表示するにする。

点線をドラッグしてチャートのサイズを変更することができます。

index.html

<!DOCTYPE html>
<html lang="jp">
<head>
<style>
html, body {
    margin: 0px;
    padding: 0px;
    width:100%;
    height:100%;
}
    
#chart {
    width: 80%;
    height: 80%;
    border: 8px dashed gray;
    border-left: none;
    border-top:none;
    cursor:all-scroll;
}
#chart svg{
    width: 100%;
    height: 100%;
    cursor: default;
}

.grid .tick line {
    stroke:#ccc;
    stroke-dasharray:1;
}

.line {
    stroke:skyblue;
    stroke-width:2;
    fill:none;
}

    
</style>
<script src="//unpkg.com/babel-standalone@6.26.0/babel.min.js"></script>
<script src="//unpkg.com/d3@4.12.2/build/d3.min.js"></script>    
</head>
<body>
<div id="chart">
    <svg></svg>
</div>



<script type="text/babel">
const data = d3.range(0, 12).map(d => { console.log(d,new Date(2017,d,1)) ;return {date:new Date(2017,d,1), value:~~(Math.random() * 99 + 1)} });
const svg = d3.select("#chart").select("svg");
const grid = svg.append("g").classed("grid", true);
const plot = svg.append("g").classed("plot", true);
const axis = svg.append("g").classed("axis", true);
const yScale = d3.scaleLinear().domain([100, 0]);
const xScale = d3.scaleTime().domain([new Date(2016,11,1), new Date(2017,12,1)]);

const lineGen = d3.line()
    .x(d => xScale(d.date))
    .y(d => yScale(d.value))


const yearFormat = d3.timeFormat("%Y年");
const monthFormat = d3.timeFormat("%m月");


render();

function render(){
    const m = {top:30, left:20, right:20, bottom:30};
    const w = svg.node().clientWidth || svg.node().parentNode.clientWidth;
    const h = svg.node().clientHeight || svg.node().parentNode.clientHeight;        
    const pw = w - (m.left + m.right);
    const ph = h - (m.top + m.bottom);
    
    
    yScale.range([0, ph]);
    xScale.range([0, pw]);
        
    //axis layer
    axis.attr("transform", `translate(${m.left}, ${m.top})`);
    
    //y axis    
    const yAxisUpdate = axis.selectAll(".yAxis").data([null]);
    const yAxisEnter = yAxisUpdate.enter().append("g").classed("yAxis", true);
    
    const yAxisRender = d3.axisRight().scale(yScale); //左側のaxisにaxisRightを使うことでラベルを内向きにする
    
    const yAxis = yAxisUpdate.merge(yAxisEnter).call(yAxisRender); 
    
    yAxis.select(".domain").remove();
    yAxis.selectAll(".tick line").remove();
    
    //tickラベルの表示位置を調整する
    yAxis.selectAll(".tick text")
        .attr("text-anchor", "end") //ラベルを右寄せにする(お好みで)
        .attr("y" , "-0.5em")
        .attr("x", "1.5em");
    
    
    //x axis
    const xAxisUpdate = axis.selectAll(".xAxis").data([null]);
    const xAxisEnter = xAxisUpdate.enter().append("g").classed("xAxis", true);
    
    const renderAxis =  d3.axisBottom().scale(xScale)
        .tickFormat(d => { 
            return monthFormat(d).replace(/^0/, "");
        })
        .tickValues(data.map(d => d.date)) //データが存在する範囲のtickだけを表示するように制限する
    
    const xAxis = xAxisUpdate.merge(xAxisEnter).call(renderAxis)
        .attr("transform", `translate(0, ${ph})`);
        
    xAxis.select(".domain").remove();
    xAxis.selectAll(".tick line").remove();
        
    //grid layer
    grid.attr("transform", `translate(${m.left}, ${m.top})`)
    
    //y grid
    const yGridUpdate = grid.selectAll(".yGrid").data([null]);
    const yGridEnter = yGridUpdate.enter().append("g").classed("yGrid", true);
    
    const yGrid = yGridUpdate.merge(yGridEnter).call( d3.axisLeft().scale(yScale).tickSizeInner(-pw).tickFormat(() => null) );

    yGrid.select(".domain").remove();
    
    //plot layer
    plot.attr("transform", `translate(${m.left}, ${m.top})`)
    
    //line
    const lineUpdate = plot.selectAll("path").data([data]);
    const lineEnter = lineUpdate.enter().append("path").classed("line", true);

    const line = lineUpdate.merge(lineEnter)
        .attr("d", lineGen);
}



//divエレメントをドラッグでリサイズできるようにする。
const dispatch = d3.dispatch("resize");    
dispatch.on("resize", render);
setResizeControler();

function setResizeControler(){
    const drag = d3.drag()
        .on("drag", resized)
    
    d3.select("#chart")    
        .call(drag);
    
    function resized(e){
        const s = d3.event.sourceEvent;
        const w = (s.pageX < 300) ? 300 : s.pageX;
        const h = (s.pageY < 200) ? 200 : s.pageY;
        
        d3.select(this)
            .style("width", `${w}px`)
            .style("height", `${h}px`)
            .attr("data-test", "test")
        
        dispatch.call("resize");
        
    }
    
}
    
    
    
</script>


</body>
</html>