App下載

js數(shù)據(jù)可視化實戰(zhàn)之本地時間軸

猿友 2020-12-30 15:17:56 瀏覽數(shù) (3510)
反饋

背景需求

使用 D3 繪制圖表一般都會繪制一個坐標軸,但是用 D3 畫過圖的同學(xué)都知道默許情況下繪制的坐標軸刻度是英文的。但是我們要的刻度是中文的。怎樣辦呢?且看本文講授如何繪制本地時間軸。

繪制效果

實現(xiàn)效果如何?先來一睹為快!

默認格式化:

d3.time.format("%b %Y")

20151021195610212

本地格式化:

zh.timeFormat("%Y年%b")

20151021195146643

實現(xiàn)思路

思路很簡單:

定義簡體中文本地化

用本地時間格式化函數(shù)格式化數(shù)軸的刻度值

關(guān)鍵技術(shù)

定義新的簡體中文本地化

//簡體中文本地化 
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]);

指定軸的比例尺和格式化函數(shù)

//時間軸 var axis = d3.svg.axis() .scale(timeScale) .tickFormat(zh.timeFormat("%Y年%b"))//指定為本地格式化函數(shù) .orient("bottom")

繪制數(shù)軸

//添加時間軸 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);

調(diào)劑刻度樣式

//旋轉(zhuǎn)文字 d3.selectAll(g.tick text).attr(transform,translate(30,20)rotate(30))

本例很簡單,可使用下面的代碼測試效果,你學(xué)會了嗎?

完全代碼

<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> 
//簡體中文本地化 
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月"] }); 
//svg寬,高 
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); 
//旋轉(zhuǎn)文字
 d3.selectAll(g.tick text).attr(transform,translate(30,20)rotate(30)) script>

可以查看更多JavaScript實例

以及JavaScript對象實例


0 人點贊