如果柱值为零,Chartjs条形图将y轴-1范围设置为+1

时间:2016-07-27 14:20:25

标签: javascript chart.js

我有一个条形图,按照我希望的方式工作,除了当数据值为零时,图表的y轴范围为-1到+1,见图。

Bar chart at zero values

代码段就是这个



@inherits System.Web.Mvc.WebViewPage

@{
	Layout = null;
}

<!DOCTYPE html>
<html>
<head>
	<title>Queue Thing</title>
</head>
<body>
<script src="~/scripts/jquery-1.9.1.js"></script>
<script src="~/scripts/jquery.signalR-2.2.0.js"></script>
<script src="~/scripts/knockout-3.4.0.js"></script>
<script src="~/scripts/Chart.js"></script>
<script src="/signalr/hubs"></script>

<h1>Dynamic Queue Details</h1>
<div style="height: 80%">
	<canvas id="myChart"></canvas>
</div>
</body>
</html>

<script type="text/javascript">
	$(function () {
		var hub = $.connection.dashHub;

		$.connection.hub.start().done(function () {
			hub.invoke('refresh', false);
		});
		
		hub.on("populateQueues",
			function(queues) {
				updateScreen(queues);
			});
	});

	function updateScreen(q) {
		var labelArray = new Array;
		var dataArray = new Array;
		jQuery.each(q, function (i, val) {
			labelArray.push(val.Name);
			dataArray.push(val.Depth);
		});
		drawMyChart(labelArray, dataArray);
	};

	function drawMyChart(la, da) {
		var myChart = new Chart(ctx, {
			type: 'bar',
			data: {
				labels: la,
				datasets: [{
					label: '# of Messages',
					data: da,
					borderWidth: 1
				}]
			},
			options: {
				maintainAspectRatio: true,
				scaleOverride: true,
				scaleStartValue: 0,
				scaleStepWidth: 100,
				scaleSteps: 9,
				scales: {
					yAxes: [{
						ticks: {
							beginAtZero: true
						}
					}]
				}
			}
		});
		myChart.draw();
	};

	var ctx = document.getElementById("myChart");
</script>
&#13;
&#13;
&#13;

如何将y轴基于零?

这是chart.js版本2.1.6 浏览器为Chrome版本52.0.2743.82 m

1 个答案:

答案 0 :(得分:0)

在您的选项中,尝试设置val sharedPreferences: SharedPreferences by inject() val sharedPreferencesEditor: SharedPreferences.Editor by inject() 而不是suggestedMin: -1,如下所示:

beginAtZero: true

此外,我建议您使用 options: { scales: { yAxes: [{ ticks: { suggestedMin: -1, } }], } } 函数来更新数据集,而不是每次都重新绘制图表。