dimple是建立在D3基础上的库,通过他我们可以操控抽象级的图表。
启动本地HTTP服务
python -m http.server
在命令行窗口下输入命令,默认是8000端口。
要想停止本地服务器,输入
Control -c
退出过程
用dimple.js来画图
function draw(data) {
/*
D3.js setup code
*/
"use strict";
var margin = 75,
width = 1400 - margin,
height = 600 - margin;
debugger;
var svg = d3.select("body")
.append("svg")
.attr("width", width + margin)
.attr("height", height + margin)
.append('g')
.attr('class','chart');
/*
Dimple.js Chart construction code
*/
var myChart = new dimple.chart(svg, data);
#表示X轴采用什么数据类型,这里是用TImeAxis函数规定的连续时间值。
#第一个变量是我们要添加哪个轴,这是是x轴。第二个变量是我们要在这个轴上写什
#么信息
#这一行的代码意思是向图表中添加一个时间轴,他由图表中的x轴表示,对应于数据##中的年分列
var x = myChart.addTimeAxis("x", "year");
#在图表中的y轴上添加连续值,对应于数据中的观赛人数列
myChart.addMeasureAxis("y", "attendance");
#addSeries规定了我们准备制作图表的类型,在这个例子中,我们传递一个dimple.pl#ot.bar类型的图表。这个null参数的意思是告诉 Dimple #不要以任何方式为柱子分面或进行组合
myChart.addSeries(null, dimple.plot.bar);
#最后一行命令用来画图
myChart.draw();
};
我们只需要更改几个简单的命令,再从新加载之后,得到的就是新的图像
原图:
更改命令:
新图:
定制Dimple图表
给图表的小圆点上色
如果我们想要将我们最新构造的一张图中的圆圈用红色来填充该怎么做呢?
在图中对小圆圈右键审查元素,可以发现小圆圈对应的是一个dimple-series-1
在HTML文件中,我们只需要向整个页面中添加一个CSS样式,确保其中含有dimple-series-1类的圆。
选择带有dimple-series-1类的圆圈元素,然后涂上红色就可以了
添加如下代码
图片变成红色了
给图表添加标题
我们添加如下代码生成标题
效果如图
但是标题效果还不是很好,有点偏,我们让标题居中
最后代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://dimplejs.org/dist/dimple.v2.0.0.min.js"></script>
<style>
circle.dimple-series-1{
fill: red;
}
h2{
text-align:center;
}
</style>
<script type="text/javascript">
function draw(data) {
/*
D3.js setup code
*/
"use strict";
var margin = 75,
width = 1400 - margin,
height = 600 - margin;
d3.select('body')
.append('h2')
.text("World Cup Attendance");
var svg = d3.select("body")
.append("svg")
.attr("width", width + margin)
.attr("height", height + margin)
.append('g')
.attr('class','chart');
/*
Dimple.js Chart construction code
*/
var myChart = new dimple.chart(svg, data);
var x = myChart.addTimeAxis("x", "year");
myChart.addMeasureAxis("y", "attendance");
myChart.addSeries(null, dimple.plot.scatter);
myChart.addSeries(null, dimple.plot.line);
myChart.draw();
};
</script>
</head>
<body>
<script type="text/javascript">
/*
Use D3 (not dimple.js) to load the TSV file
and pass the contents of it to the draw function
*/
d3.tsv("world_cup.tsv", draw);
</script>
</body>
</html>