【发布时间】:2015-05-22 13:16:28
【问题描述】:
寻找一种方法使以下图表的顶部从 0 变为 1。
我可以在valueAxes 配置部分中设置minimum: 1,但这会强制 1 成为它将显示的下限,无论该行出现在哪里。
我在 amcharts 文档中没有看到类似的东西,所以我实际上认为这不可能,但我经常错了,所以我希望是这样。
【问题讨论】:
标签: javascript amcharts
寻找一种方法使以下图表的顶部从 0 变为 1。
我可以在valueAxes 配置部分中设置minimum: 1,但这会强制 1 成为它将显示的下限,无论该行出现在哪里。
我在 amcharts 文档中没有看到类似的东西,所以我实际上认为这不可能,但我经常错了,所以我希望是这样。
【问题讨论】:
标签: javascript amcharts
对于您的需求没有单一的解决方案。
将minimum: 1 与strictMinMax 结合使用(或不结合)将强制比例从特定数字开始,而不管图表变量的实际范围如何。
您可以尝试更多“参与”的方法。
在图表构建之前,循环浏览图表数据并仅在有接近它的值时设置minimum。
/**
* Create the chart
*/
var chart = AmCharts.makeChart("chartdiv", {
"type": "serial",
"theme": "light",
"path": "http://www.amcharts.com/lib/3/",
"dataProvider": [{
"year": "1950",
"value": 9
}, {
"year": "1951",
"value": 30
}, {
"year": "1952",
"value": 35
}, {
"year": "1953",
"value": 25
}, {
"year": "1954",
"value": 70
}, {
"year": "1955",
"value": 45
}, {
"year": "1956",
"value": 55
}],
"valueAxes": [{
"reversed": true,
// these are the made up properties that are used by our custom code
// set value axis minimum with "tentativeMinimum" if there are
// values withing "minimumThreshold" to it
"tentativeMinimum": 1,
"minimumThreshold": 9
}],
"graphs": [{
"id": "g1",
"bullet": "round",
"lineThickness": 2,
"type": "smoothedLine",
"valueField": "value"
}],
"categoryField": "year",
"categoryAxis": {
"labelsEnabled": false,
}
});
/**
* Add chart pre-processor
*/
AmCharts.addInitHandler( function( chart ) {
// check if there are any value axes defined
if ( typeof chart.valueAxes !== "object" || ! chart.valueAxes.length )
return;
// check if chart's value axis has "tentativeMinimum" set
// For the sake of simplicity we're just gonna take the first
// value axis and first graph.
// Normally we would want to check all value axes and their attached
// graphs to check for their respective values.
var axis = chart.valueAxes[0];
if ( axis.tentativeMinimum === undefined || axis.minimumThreshold === undefined )
return;
// get first charts valueField to check agains
var field = chart.graphs[0].valueField;
// cycle through the data
var min;
for ( var x = 0; x < chart.dataProvider.length; x++ ) {
if ( min === undefined || ( chart.dataProvider[x][field] < min ) )
min = chart.dataProvider[x][field];
}
// check if min is within the threshold
if ( min <= ( axis.tentativeMinimum + axis.minimumThreshold ) )
axis.minimum = axis.tentativeMinimum;
}, [ "serial" ] );
#chartdiv {
width: 400px;
height: 300px;
}
<script src="http://www.amcharts.com/lib/3/amcharts.js"></script>
<script src="http://www.amcharts.com/lib/3/serial.js"></script>
<script src="http://www.amcharts.com/lib/3/themes/light.js"></script>
<div id="chartdiv"></div>
使用值轴'labelFunction 简单地将零替换为 1:
var chart = AmCharts.makeChart("chartdiv", {
...
"valueAxes": [{
"reversed": true,
"labelFunction": function( label ) {
return label === 0 ? 1 : label;
}
}],
...
});
请注意,这不会影响实际值轴比例。但是,差异可能并不明显。
【讨论】: