背景需求
使用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: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"]
});
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>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53