【发布时间】:2019-12-25 14:09:30
【问题描述】:
我想通过指定中间的填充将条从 x 轴向上提升。我试图探索几乎所有的属性,但找不到这样做的方法。我使用chart.js 作为库。
红框标记的区域
注意:我无法使用 stackoverflow 工具插入图像,因此添加了直接 url
我尝试为栏的底部提供边框宽度并将其颜色设置为透明,但这也不起作用。
【问题讨论】:
标签: javascript charts html5-canvas chart.js bar-chart
我想通过指定中间的填充将条从 x 轴向上提升。我试图探索几乎所有的属性,但找不到这样做的方法。我使用chart.js 作为库。
红框标记的区域
注意:我无法使用 stackoverflow 工具插入图像,因此添加了直接 url
我尝试为栏的底部提供边框宽度并将其颜色设置为透明,但这也不起作用。
【问题讨论】:
标签: javascript charts html5-canvas chart.js bar-chart
您可以使用堆积条形图。
使用第一个系列作为与轴的偏移量,颜色为透明。
然后将实际数据减少偏移量,因此条形高度将以正确的值结束。
请参阅以下工作 sn-p...
$(document).ready(function() {
var offset = [200, 200, 200, 200];
var data = [7900, 5400, 4300, 4300];
var ctx = document.getElementById('bar-chart');
var data = {
labels: ['June 9', 'June 11', 'June 13', 'June 15'],
datasets: [{
data: offset,
backgroundColor: 'transparent'
}, {
data: data.map(function (value, index) {
return value - offset[index];
}),
backgroundColor: 'orange'
}]
}
var myChart = new Chart(ctx, {
type: 'bar',
data: data,
options: {
legend: {
display: false
},
tooltips: {
enabled: false
},
scales: {
yAxes: [{
stacked: true
}]
}
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.bundle.min.js"></script>
<canvas id="bar-chart"></canvas>
【讨论】:
如果您需要一个固定的偏移量,那么@WhiteHat 的答案可能是最简单的。如果您需要设置每个柱的底部,那么您应该考虑使用 this chart.js plugin 更改为 Box & Whisker 类型图表。
关闭边框以隐藏胡须。将您的数据设置为 [[startValue, startValue, endValue, endValue], ...]
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'boxplot',
data: {
labels: ['Red', 'Blue', 'Yellow'],
datasets: [{
label: '# of Votes',
data: [
[1, 1, 12, 12],
[2, 2, 8, 8],
[3, 3, 10, 10]
],
backgroundColor: 'orange',
borderColor: 'transparent',
borderWidth: 0
}]
},
options: {
legend: {
display: false
},
tooltips: {
enabled: false
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.bundle.min.js"></script>
<script src="https://unpkg.com/chartjs-chart-box-and-violin-plot@2.1.0/build/Chart.BoxPlot.min.js"></script>
<canvas id="myChart" width="400" height="400"></canvas>
【讨论】: