您的位置:首页 > Web前端 > JavaScript

【D3.js数据可视化实战】--(2)本地时间轴

2015-10-21 20:18 926 查看
背景需求

绘制效果

实现思路

关键技术

完整代码

背景需求

使用D3绘制图表一般都会绘制一个坐标轴,但是用D3画过图的同学都知道默认情况下绘制的坐标轴刻度是英文的。但是我们要的刻度是中文的。怎么办呢?且看本文讲解如何绘制本地时间轴。

绘制效果

实现效果如何,先来一睹为快!

默认格式化:

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: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"],
shortDays: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"],
months: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
shortMonths: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"]
});


定义时间比例尺

//时间比例尺
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)')


本例很简单,可以使用下面的代码测试效果,你学会了吗?

完整代码

<!DOCTYPE html>
<meta charset="utf-8">
<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: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"], shortDays: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"], months: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"], shortMonths: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"] });
//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);
//旋转文字 d3.selectAll('g.tick text').attr('transform','translate(30,20)rotate(30)')
</script>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  d3 数据可视化 d3.js