javascript - ChartJS – 将基线设置在零以上
问题描述
我正在尝试使用Chart.js
. 我试图让图表显示条高于一个向上,而低于 1 的值(例如 0.8)指向向下。如果它包含低于零的值,则会显示与图表相同的内容。本质上,我试图将 Y 轴的基线更改为 1 而不是 0。
像这样的东西:
解决方案
最好的方法(显然还有更多的工作)是创建一个自定义轴。Chart.js 在这里解释了如何做到这一点:
https://www.chartjs.org/docs/latest/developers/axes.html
我还创建了一个小提琴,其中数据值由一组基线修改。我还修改了工具提示和 y 轴标签,以便所有内容都基于基线显示。它不像自定义轴那样优雅,但它很快并且可以完成工作(假设基线是已知的)。你可以在这里查看小提琴:
https://jsfiddle.net/tkngc02h/1/
而且,如果您只想查看代码,这里是:
<!doctype html>
<html>
<head>
<title>Line Styles</title>
<script src="https://www.chartjs.org/dist/2.9.3/Chart.min.js"></script>
<script src="https://www.chartjs.org/samples/latest/utils.js"></script>
<style>
canvas{
-moz-user-select: none;
-webkit-user-select: none;
-ms-user-select: none;
}
</style>
</head>
<body>
<div style="width:75%;">
<canvas id="canvas"></canvas>
</div>
<script>
var baseline = 1;
var config = {
type: 'bar',
data: {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [{
label: 'TestData',
fill: false,
backgroundColor: window.chartColors.blue,
borderColor: window.chartColors.blue,
data: [
0 - baseline,
1.8 - baseline,
2.1 - baseline,
-0.2 - baseline,
1.3 - baseline,
-0.5 - baseline,
-0.23 - baseline,
0 - baseline
],
}]
},
options: {
responsive: true,
title: {
display: true,
text: 'Chart.js Line Chart',
},
tooltips: {
mode: 'index',
intersect: false,
callbacks: {
// Use the footer callback to display the sum of the items showing in the tooltip
label: function(tooltipItem, data) {
var label = data.datasets[tooltipItem.datasetIndex].label || '';
if (label) {
label += ': ';
}
label += tooltipItem.yLabel + baseline;
return label;
},
},
},
hover: {
mode: 'nearest',
intersect: true
},
scales: {
xAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Month'
}
}],
yAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Value',
},
ticks: {
// Include a dollar sign in the ticks
callback: function(value, index, values) {
return value + baseline;
}
}
}]
}
}
};
window.onload = function() {
var ctx = document.getElementById('canvas').getContext('2d');
window.myLine = new Chart(ctx, config);
};
</script>
</body>
</html>
推荐阅读
- sql - SQL Server:仅当同一个表中的另一列是特定值时,如何强制一列中的 NOT NULL?
- c++ - 如何在 4x4 数组中随机选择 3 个不同的位置
- java - 我怎样才能更好地将我的用户输入法调用到我的主要方法中,以检查获胜条件?
- hbase - HBASE - 增量和增量列值无法在分布式设置中增加计数器
- java - Intellij Idea 评论错误
- php - DATE_ADD(NOW(), INTERVAL 5 MINUTE 插入
- ruby-on-rails - Ruby 中的领域特定语言和翻译
- r - R:函数内部 ggplot 的无法解释的行为
- reactjs - 在 react-chartjs-2 中将背景颜色更改为渐变
- c# - 如果项目存在于 C#/WPF 的 ObservableCollection 中,则查找数字的索引