背景需求
使用D3繪制圖表1般都會繪制1個坐標軸,但是用D3畫過圖的同學都知道默許情況下繪制的坐標軸刻度是英文的。但是我們要的刻度是中文的。怎樣辦呢?且看本文講授如何繪制本地時間軸。
繪制效果
實現效果如何,先來1睹為快!
d3.time.format("%b %Y")
zh.timeFormat("%Y年%b")
實現思路
思路很簡單:
-
定義簡體中文本地化
-
用本地時間格式化函數格式化數軸的刻度值
關鍵技術
var zh = d3.locale({
decimal: ".",
thousands: ",",
grouping: [3],
currency: ["¥", ""],
dateTime: "%a %b %e %X %Y",
date: "%Y/%-m/%-d",
time: "%H:%M:%S",
periods: ["上午", "下午"],
days: ["星期日", "星期1", "星期2", "星期3", "星期4", "星期5", "星期6"],
shortDays: ["星期日", "星期1", "星期2", "星期3", "星期4", "星期5", "星期6"],
months: ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "101月", "102月"],
shortMonths: ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "101月", "102月"]
});
var timeScale = d3.time.scale()
.domain([new Date(2015, 0, 1), new Date(2016, 1, 1)])
.range([0, width-40]);
var axis = d3.svg.axis()
.scale(timeScale)
.tickFormat(zh.timeFormat("%Y年%b")) .orient("bottom")
var svg = d3.select("body").append("svg")
.attr("width", width+200)
.attr("height", height)
.append("g")
.attr("class", "axis")
.attr("transform", "translate(" + 20 + "," + height/2 + ")")
.call(axis);
d3.selectAll(g.tick text).attr(transform,translate(30,20)rotate(30))
本例很簡單,可使用下面的代碼測試效果,你學會了嗎?
完全代碼
<meta charset="utf⑻"> <style> body{ font-weight:bold; } .axis path, .axis line { fill: none; stroke: #000; shape-rendering: crispEdges; } style> <body> <script src="../../d3.js">script> <script> var zh = d3.locale({
decimal: ".",
thousands: ",",
grouping: [3],
currency: ["¥", ""],
dateTime: "%a %b %e %X %Y",
date: "%Y/%-m/%-d",
time: "%H:%M:%S",
periods: ["上午", "下午"],
days: ["星期日", "星期1", "星期2", "星期3", "星期4", "星期5", "星期6"],
shortDays: ["星期日", "星期1", "星期2", "星期3", "星期4", "星期5", "星期6"],
months: ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "101月", "102月"],
shortMonths: ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "101月", "102月"]
}); var width = 1000,height = 500; var timeScale = d3.time.scale()
.domain([new Date(2015, 0, 1), new Date(2016, 1, 1)])
.range([0, width-40]); var axis = d3.svg.axis()
.scale(timeScale)
.tickFormat(zh.timeFormat("%Y年%b"))
.orient("bottom") var svg = d3.select("body").append("svg")
.attr("width", width+200)
.attr("height", height)
.append("g")
.attr("class", "axis")
.attr("transform", "translate(" + 20 + "," + height/2 + ")")
.call(axis); d3.selectAll(g.tick text).attr(transform,translate(30,20)rotate(30)) script>