Skip to content

Instantly share code, notes, and snippets.

@mforando
Last active February 19, 2019 15:44
Show Gist options
  • Save mforando/548ff897997f73784857703e0c01e800 to your computer and use it in GitHub Desktop.
Save mforando/548ff897997f73784857703e0c01e800 to your computer and use it in GitHub Desktop.
Label start of month only
license: mit
<!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>
var width = 800;
var padding = 20;
//range = four months
var dates = [new Date(2018, 0, 1),
new Date(2018, 1, 1),
new Date(2018, 2, 1),
new Date(2018, 3, 1)]
var x = d3.scaleTime().range([0, width]).domain(d3.extent(dates,function(d){return d}))
// Feel free to change or delete any of the code you see in this editor!
var svg = d3.select("body").append("svg")
.attr("width", 960)
.attr("height", 500)
.style("margin",padding)
.style("overflow","visible")
svg.append("g")
.attr("class", "axis")
.attr("transform", "translate(0," + 50 + ")")
.call(d3.axisBottom(x)
.tickFormat(d3.timeFormat("%B"))
)
.selectAll("text")
.style("text-anchor", "end")
.attr("dx", "-.8em")
.attr("dy", ".15em")
.attr("transform", "rotate(-65)");
svg.append("text")
.attr("x",0)
.attr("y",45)
.text("Default Axis")
.style("fill","red")
.style("font-family","Helvetica")
var dateTicks = d3.timeMonths(x.domain()[0],
x.domain()[1].setDate(x.domain()[1].getDate() + 1))
svg.append("g")
.attr("class", "axis")
.attr("transform", "translate(0," + 150 + ")")
.call(d3.axisBottom(x)
.tickFormat(d3.timeFormat("%B"))
.tickValues(dateTicks)
//dateTicks)
)
.selectAll("text")
.style("text-anchor", "end")
.attr("dx", "-.8em")
.attr("dy", ".15em")
.attr("transform", "rotate(-65)");
svg.append("text")
.attr("x",0)
.attr("y",145)
.text("Modified Axis")
.style("fill","blue")
.style("font-family","Helvetica")
var dateTicks = d3.timeMonths(x.domain()[0],
x.domain()[1].setDate(x.domain()[1].getDate() + 1))
svg.append("g")
.attr("class", "axis")
.attr("transform", "translate(0," + 250 + ")")
.call(d3.axisBottom(x)
//.tickFormat(d3.timeFormat("%B"))
.tickValues([new Date(2018, 0, 1),
new Date(2018, 1, 1),
new Date(2018, 1, 15),
new Date(2018, 3, 1)])
//dateTicks)
)
.selectAll("text")
.style("text-anchor", "end")
.attr("dx", "-.8em")
.attr("dy", ".15em")
.attr("transform", "rotate(-65)");
svg.append("text")
.attr("x",0)
.attr("y",245)
.text("Modified Axis - Random Ticks")
.style("fill","orange")
.style("font-family","Helvetica")
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment