Jim*_*ery 3 javascript chart.js
我使用Chart.js v2.5.0创建这样的图表:
请注意,有时条形图会越过红色虚线.有时红色虚线将处于不同的位置(通常为25,但在某些月份将处于其他水平).
我的问题是我希望红色虚线延伸到列的整个宽度.正如您在第一列中看到的那样,红色虚线仅进入色谱柱的一半.我在图表的另一端有同样的问题,红色虚线只进入了列的一半.
我目前的实现是混合图表,一个是条形图,另一个是折线图 - 数据如下:
data = {
labels: ['Jan 21st', 'Feb 21st', 'Mar 21st', 'Apr 21st']
datasets: [
{
type: 'bar',
label: 'A',
data: [10, 25, 18, 37],
},
{
type: 'line',
label: 'B',
data: [25, 25, 25, 25],
fill: false,
borderWidth: 1,
borderColor: '#f00',
borderDash: [5,4],
lineTension: 0,
steppedLine: true
}
]
}
Run Code Online (Sandbox Code Playgroud)
Chart.js是否有选项或方法使红色虚线延伸到整列宽度?
我有另一个想法,但我不确定这是否可行:我可以使用红色虚线条形图,只显示条形图的顶行吗?
不幸的是,没有办法"配置"图表来实现你想要的.这一切都与折线图缩放图的工作方式有关.话虽如此,你仍然可以通过使用一些"虚拟"数据欺骗 chart.js来实现这种行为.
基本上,您创建一个"虚拟"的第一个和最后一个标签.然后将相应的"虚拟"第一个和最后一个值添加到条形数据数组中(此数据将永远不会显示).然后将相应的"虚拟"第一个和最后一个值添加到行数据数组中,但请确保将值设置为与下一个/ prev值相同以最终得到一条直线(否则您的行将在开头和结尾处成角度).这就是我的意思.
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['dummy1', 'Jan 21st', 'Feb 21st', 'Mar 21st', 'Apr 21st', 'dummy2'],
datasets: [
{
type: 'bar',
label: 'A',
// the 1st and last value are placeholders and never get displayed on the chart
data: [0, 10, 25, 18, 37, 0],
},
{
type: 'line',
label: 'B',
// the 1st and last value are placeholders and never get displayed on the chart
// to get a straight line, the 1st and last values must match the same value as
// the next/prev respectively
data: [25, 25, 25, 25, 25, 25],
fill: false,
borderWidth: 1,
borderColor: '#f00',
borderDash: [5,4],
lineTension: 0,
steppedLine: true
}
]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}],
xAxes: [{
// exclude the 1st and last label placeholders by specifying the min/mix ticks
ticks: {
min: 'Jan 21st',
max: 'Apr 21st',
}
}],
}
}
});
Run Code Online (Sandbox Code Playgroud)
查看此codepen示例以查看它的实际效果.