使用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>
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文:http://blog.csdn.net/tianxuzhang/article/details/49308933