flot柱形图表x轴显示相关问题

[文章作者:磨延城 转载请注明原文出处: https://mo2g.com/view/146/ ]
最近负责开发一个监控项目,需要把统计结果通过图表的形式展现出来.这里使用到了jquery的flot插件,github项目地址:https://github.com/flot/flot.这回,就记录一下,开发过程中遇上的一些问题,以及解决方案.
最近负责开发一个监控项目,需要把统计结果通过图表的形式展现出来。这里使用到了jquery的flot插件,github项目地址:https://github.com/flot/flot。这回,就记录一下,开发过程中遇上的一些问题,以及解决方案。
1)categories柱形图,当显示的数据太多,会导致x轴的标识信息重叠,如下图所示:

为了解决X轴标签的重叠问题,我在网上找了好多资料,有网友使用CSS来控制标签旋转,避免重叠。CSS样式类似代码:
.flot-x-axis. tickLabel {
-o-transform:rotate(40deg);
-moz-transform:rotate(40deg);
-webkit-transform:rotate(40deg);
filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3);
}
效果图
然而,这不是我想要的效果,X轴的信息过于密集,不是很美观,可不可以精简一下X轴,不显示那么多刻度呢?例如5~10天显示一个刻度,类似下图:

这样既清爽,又解决了重叠的问题了。
接下来就给大家讲解flot提供的ticks参数,可以自定义显示的标签。
ticks对应的二维数组结构解析:
ticks: [ [ 对应轴上标签的索引,从0开始计算, 对应标签要显示的内容 ] ]
示例如下:
xaxis: {
mode: "categories",
ticks: [
[0,'2015-08-01'],[5,'2015-08-06'],[10,'2015-08-11'],[15,'2015-08-16'],
[20,'2015-08-21'],[25,'2015-08-26'],[30,'2015-08-31']
]
}这里,我们可以改进一下,使用函数来返回数据
xaxis: {
mode: "categories",
ticks: x_label(flot_data,9)
}x_label函数的实现代码如下:
function x_label(data,max) {
var label = [],
end = data.length - 1,
index = 0;
$.each(data,function(i,k) {
if( Math.floor(i * max / end) == index ) {
label.push([i,k[0]]);
index++;
}
});
return label;
}完整的代码如下,可以直接运行看效果。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Flot Examples: Categories</title>
<link href="http://www.flotcharts.org/flot/examples/examples.css" rel="stylesheet" type="text/css">
<!--[if lte IE 8]><script src="http://www.flotcharts.org/excanvas.min.js"></script><![endif]-->
<script src="http://www.flotcharts.org/flot/jquery.js"></script>
<script src="http://www.flotcharts.org/flot/jquery.flot.js"></script>
<script src="http://www.flotcharts.org/flot/jquery.flot.categories.js"></script>
<script>
$(function() {
var flot_data = [["2015-08-01", 10],["2015-08-02", 10],["2015-08-03", 10],["2015-08-04", 10],["2015-08-05", 10],["2015-08-06", 10],["2015-08-07", 10],
["2015-08-08", 10],["2015-08-09", 10],["2015-08-10", 10],["2015-08-11", 10],["2015-08-12", 10],["2015-08-13", 10],["2015-08-14", 10],["2015-08-15", 10],
["2015-08-16", 10],["2015-08-17", 10],["2015-08-18", 10],["2015-08-19", 10],["2015-08-20", 10],["2015-08-21", 10],["2015-08-22", 10],["2015-08-23", 10],
["2015-08-24", 10],["2015-08-25", 10],["2015-08-26", 10],["2015-08-27", 10],["2015-08-28", 10],["2015-08-29", 10],["2015-08-30", 10],["2015-08-31", 10],
];
$.plot("#placeholder", [ flot_data ], {
series: {
bars: {
show: true,
barWidth: 0.6,
align: "center"
}
},
xaxis: {
mode: "categories",
ticks: x_label(flot_data,10)
}
});
});
function x_label(data,max) {
var label = [],
end = data.length - 1,
index = 0;
$.each(data,function(i,k) {
if( Math.floor(i * max / end) == index ) {
label.push([i,k[0]]);
index++;
}
});
return label;
}
</script>
</head>
<body>
<div id="header">
<h2>Categories</h2>
</div>
<div class="demo-container">
<div id="placeholder" class="demo-placeholder"></div>
</div>
</body>
</html>
我来说两句: