Built with blockbuilder.org
forked from ritchieking's block: fresh block
forked from ritchieking's block: Axis formats based on width
Built with blockbuilder.org
forked from ritchieking's block: fresh block
forked from ritchieking's block: Axis formats based on width
<!DOCTYPE html> | |
<meta charset="utf-8"> | |
<style> | |
.axis text { | |
font: 10px sans-serif; | |
} | |
.axis line, | |
.axis path { | |
fill: none; | |
stroke: #000; | |
shape-rendering: crispEdges; | |
} | |
</style> | |
<body> | |
<script src="//d3js.org/d3.v3.min.js"></script> | |
<script src="https://d3js.org/d3-time.v0.2.min.js"></script> | |
<script src="https://d3js.org/d3-time-format.v0.3.min.js"></script> | |
<script> | |
Object.assign(d3, d3_time_format); | |
Object.assign(d3, d3_time); | |
var formatMillisecond = {long: ".%L", short: ".%L"}, | |
formatSecond = {long: ":%S", short: ":%S"}, | |
formatMinute = {long: "%I:%M", short: "%I:%M"}, | |
formatHour = {long: "%I %p", short: "%I %p"}, | |
formatDay = {long: "%a %d", short: "%a %d"}, | |
formatWeek = {long: "%b %d", short: "%b %d"}, | |
formatMonth = {long: "%B", short: "%b"}, | |
formatYear = {long: "%Y", short: "'%y"}; | |
function multiFormat (size) { | |
return function (date) { | |
return (d3.timeSecond(date) < date ? d3.timeFormat(formatMillisecond[size]) | |
: d3.timeMinute(date) < date ? d3.timeFormat(formatSecond[size]) | |
: d3.timeHour(date) < date ? d3.timeFormat(formatMinute[size]) | |
: d3.timeDay(date) < date ? d3.timeFormat(formatHour[size]) | |
: d3.timeMonth(date) < date ? (d3.timeWeek(date) < date ? d3.timeFormat(formatDay[size]) : d3.timeFormat(formatWeek[size])) | |
: d3.timeYear(date) < date ? d3.timeFormat(formatMonth[size]) | |
: d3.timeFormat(formatYear[size]))(date); | |
} | |
} | |
var margin = {top: 250, right: 40, bottom: 250, left: 40}, | |
width = 960 - margin.left - margin.right, | |
height = 500 - margin.top - margin.bottom; | |
var x = d3.time.scale() | |
.domain([new Date(2012, 0, 1), new Date(2013, 0, 1)]) | |
.range([0, width]); | |
var xAxis = d3.svg.axis() | |
.scale(x) | |
.tickFormat(multiFormat('short')); | |
var svg = d3.select("body").append("svg") | |
.attr("width", width + margin.left + margin.right) | |
.attr("height", height + margin.top + margin.bottom) | |
.append("g") | |
.attr("transform", "translate(" + margin.left + "," + margin.top + ")"); | |
var axis = svg.append("g") | |
.attr("class", "x axis") | |
.attr("transform", "translate(0," + height + ")") | |
.call(xAxis); | |
</script> |