chart.js - 图表 js 在 y 轴上有一个跨越负/正的条形图
问题描述
chartjs 中有没有办法让条形图跨越零线?例如,假设我有一个酒吧
data:[x:1, y:100]
我如何告诉它跨越 y 轴从 -100 到 100(而不是从 0 到 100)?
我在这里有一个游乐场,我可以对每个小节做负数或正数,但不能对一个小节同时做。
解决方案
这可以从Chart.js v2.9.0 开始,现在支持浮动条。现在可以使用语法指定单个条形图[min, max]
。
<html>
<head>
<title>Floating Bars</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<style>
canvas {
-moz-user-select: none;
-webkit-user-select: none;
-ms-user-select: none;
}
</style>
</head>
<body>
<div>
<canvas id="canvas" height="120"></canvas>
</div>
<script>
var chartData = {
labels: [1,2,3,4,5,6],
datasets: [{
type: 'bar',
label: 'Red Bar',
borderColor: 'black',
borderWidth: 1,
backgroundColor: 'rgba(128,0,0,0.2)',
data: [[0, 100], [-100, 100], [-30, 40], 0, 0, 0],
}, {
type: 'bar',
label: 'Green Bar',
backgroundColor: 'rgba(0,128,0,0.2)',
borderColor: 'black',
borderWidth: 1,
data: [0, 0, 0, 0, [-50, 70], 100],
}
]
};
window.onload = function() {
var ctx = document.getElementById('canvas').getContext('2d');
window.myBar = new Chart(ctx, {
type: 'bar',
data: chartData,
options: {
scaleBeginAtZero: false,
responsive: true,
spanGaps: true,
tooltips: {
mode: 'index',
intersect: true
},
scales: {
xAxes: [{
gridLines: {
display: false
},
}],
yAxes: [{
type: 'linear',
ticks: {
beginAtZero: false,
min:-100,
max:100,
stepSize:30
}
}],
}
}
});
};
</script>
</body>
</html>
推荐阅读
- ruby-on-rails - Base64 编码参数的 Rails 路由约束
- python-3.x - 如何摆脱输出中的引号和括号?
- google-chrome-extension - Chrome 扩展未安装:CRX_HEADER_INVALID
- sql - 插入或更新期间列上的 Postgres 和数学
- html - 我必须使用 ActiveXObject 在 html 中打开 powerpoint 演示文稿吗
- python - 训练模型后从 Keras/Tensorflow 获取预测
- xaml - 列表视图中项目的最大高度?
- php - 客户端错误:`GET https://api.powerbi.com/v1.0/myorg/datasets` 导致 `401 Unauthorized` 响应 Power BI REST api
- python - 我有一些文件格式的数据。我想知道每行的第一个字符串是什么,并计算它们重复了多少次
- python - Python 2.7 fnmatch 不编辑文本