【发布时间】:2017-05-25 02:01:46
【问题描述】:
【问题讨论】:
标签: javascript charts html5-canvas chart.js chart.js2
【问题讨论】:
标签: javascript charts html5-canvas chart.js chart.js2
在 Chart.js 中没有简单的方法可以做到这一点(例如特定的“100% 堆叠条形”类型)。您需要的是两个堆叠的水平条。
首先,将您的chart-type 定义为horizontalBar
// html
<canvas id="chart" height="20"></canvas>
// javascript
var ctx = document.getElementById('chart');
var bar_chart = new Chart(ctx, {
type: 'horizontalBar' // this will give you a horizontal bar.
// ...
};
为了有一个而不是两个,它们需要堆叠。您还需要隐藏刻度。或者,您可以隐藏图例和工具提示。这都是在options中配置的:
var bar_chart = new Chart(ctx, {
// ...
options: {
legend: {
display: false // hides the legend
},
tooltips: {
enabled: false // hides the tooltip.
}
scales: {
xAxes: [{
display: false, // hides the horizontal scale
stacked: true // stacks the bars on the x axis
}],
yAxes: [{
display: false, // hides the vertical scale
stacked: true // stacks the bars on the y axis
}]
}
}
};
由于堆叠条相互重叠,您的第一个数据集包含您的值 (57.866),第二个数据集对应于 max - value。以下是考虑value = 57866 和max = 80000 的示例:
var value = 57866; // your value
var max = 80000; // the max
var bar_chart = new Chart(ctx, {
// ...
datasets: [{
data: [value],
backgroundColor: "rgba(51,230,125,1)"
}, {
data: [max - value],
backgroundColor: "lightgrey"
}]
};
这是带有完整代码的jsfiddle。
【讨论】:
除了@Tarek 的回答,
如果需要获取bar中的百分比值,
https://jsfiddle.net/akshaykarajgikar/bk04frdn/53/
依赖关系:
https://chartjs-plugin-datalabels.netlify.app/
var bar_ctx = document.getElementById('bar-chart');
var bar_chart = new Chart(bar_ctx, {
type: 'horizontalBar',
data: {
labels: [],
datasets: [{
data: [57.866],
backgroundColor: "#00BC43",
datalabels: {
color: 'white' //Color for percentage value
}
}, {
data: [100 - 57.866],
backgroundColor: "lightgrey",
hoverBackgroundColor: "lightgrey",
datalabels: {
color: 'lightgray' // Make the color of the second bar percentage value same as the color of the bar
}
}, ]
},
options: {
legend: {
display: false
},
tooltips: {
enabled: false
},
scales: {
xAxes: [{
display: false,
stacked: true
}],
yAxes: [{
display: false,
stacked: true
}],
}, // scales
plugins: { // PROVIDE PLUGINS where you can specify custom style
datalabels: {
align: "start",
anchor: "end",
backgroundColor: null,
borderColor: null,
borderRadius: 4,
borderWidth: 1,
font: {
size: 20,
weight: "bold", //Provide Font family for fancier look
},
offset: 10,
formatter: function(value, context) {
return context.chart.data.labels[context.dataIndex]; //Provide value of the percentage manually or through data
},
},
},
}, // options
});
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@0.7.0"></script>
<canvas id="bar-chart" height="20"></canvas>
【讨论】: