我一直在使用 Chartjs 来生成类似 highcharts 的东西但无法接近。应用程序已完成,购买 highcharts 似乎很浪费,从 Chartjs 迁移到这个单一图表。
Chartjs 有没有办法输出类似的东西?我确实尝试在单独的 Canvas 中并排创建两个水平条形图;当我看到输出时;这种行为不是我想要的。
最佳答案
您可以使用水平 stacked具有两个数据集的条形图。向左侧数据集(男性)添加负值,但在 xAxis 和工具提示的回调中显示绝对值。
var ctx = document.getElementById('myChart').getContext('2d');
var data = {
labels: ["20-30", "10-20", "0-10"],
datasets: [{
label: "Male",
backgroundColor: "rgba(54, 162, 235, 0.2)",
borderColor: "rgb(54, 162, 235)",
borderWidth: 2,
data: [-65, -59, -20],
}, {
label: "Female",
backgroundColor: "rgba(255,99,132,0.2)",
borderColor: "rgba(255,99,132,1)",
borderWidth: 2,
data: [72, 45, 18],
},
]
};
var myBarChart = new Chart(ctx, {
type: 'horizontalBar',
data: data,
options: {
scales: {
yAxes: [{
stacked: true
}],
xAxes: [{
ticks: {
callback: function(value, index, values) {
return Math.abs(value);
}
}
}]
},
tooltips: {
callbacks: {
label: function(tooltipItems, data) {
return data.datasets[tooltipItems.datasetIndex].label + ": " + Math.abs(tooltipItems.xLabel);
}
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.min.js"></script>
<canvas id="myChart"></canvas>
关于highcharts - Chartjs中highcharts的负条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48444483/