介绍
在上一篇文章的结尾,对生成的可视化图,我们提到了许多待改进的地方。这儿就先来讨论下图例的显示。
图例的主要目的是说明图表中各种符号和颜色所代表的内容及指标的说明。对于我们之前生成的line chart,需要用图例说明每条曲线所代表的具体含义是什么。总结两点基本原则如下:
1. 图例中要对应曲线的颜色,并指出对应的医疗机构名称;
2. 图例要放在适当的位置,以便起到恰如其分的指示作用。
本文下面会实现两种不同的实现方法,并讨论其不同之处。
代码示例
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>全国医疗卫生机构医疗服务量</title>
<link rel="stylesheet" type="text/css" href="css/styles.css"/>
<script type="text/javascript" src="js/d3.min.js"></script>
</head>
<body>
<script type="text/javascript">
function lineChart() {
var _chart = {};
var _width = screen.width * 0.9, _height = 350,
_margins = {top: 30, left: 50, right: 130, bottom: 60}, //expand margin for legend rendor
_legendbottom = 30, //area for legend in Method 2
_legendright = 100, //area for legend in Method 1
_x, _y,
_names = [], //keep name list for the chart
_data = [],
//_colors = d3.scale.category10(),
_colors, //define colors according to name list
_svg,
_bodyG,
_line;
_chart.render = function () {
if (!_svg) {
_svg = d3.select("body").append("div")
.style("text-align", "center")
.append("svg")
.attr("height", _height)
.attr("width", _width);
renderAxes(_svg);
defineBodyClip(_svg);
}
renderBody(_svg);
};
function renderAxes(svg) {
var axesG = svg.append("g")
.attr("class", "axes");
renderXAxis(axesG);
renderYAxis(axesG);
}
function renderXAxis(axesG){
var xAxis = d3.svg.axis()
.scale(_x.range([0, quadrantWidth()]))
.orient("bottom");
axesG.append("g")
.attr("class", "x axis")
.attr("transform", function () {
return "translate(" + xStart() + "," + yStart() + ")";
})
.call(xAxis);
d3.selectAll("g.x g.tick")
.append(&