我根据需要在悬停时获取数据值:
...但我也想在每个栏的顶部添加一个值,如下所示:
如何获取计算数据并将其嵌入到每个条中?
我的代码如下:
HTML
<div class="graph_container">
<canvas id="priceComplianceBarChart"></canvas>
</div>
查询
Chart.defaults.global.defaultFontFamily = "Georgia";
var ctxBarChart =
$("#priceComplianceBarChart").get(0).getContext("2d");
var barChartData = {
labels: ["Bix Produce", "Capitol City", "Charlies Portland",
"Costa Fruit and Produce", "Get Fresh Sales", "Loffredo East", "Loffredo
West", "Paragon", "Piazza Produce"],
datasets: [
{
label: "Price Compliant",
backgroundColor: "rgba(34,139,34,0.5)",
hoverBackgroundColor: "rgba(34,139,34,1)",
data: [17724, 5565, 3806, 5925, 5721, 6635, 14080, 9027,
25553]
},
{
label: "Non-Compliant",
backgroundColor: "rgba(255, 0, 0, 0.5)",
hoverBackgroundColor: "rgba(255, 0, 0, 1)",
// The vals below have been multiplied by 10 (a 0
appended) so that the values are at least visible to the naked eye
data: [170, 10, 180, 140, 30, 10, 50, 100, 10]
}
]
}
var optionsBar = {
scales: {
xAxes: [
{
stacked: true
}
],
yAxes: [
{
stacked: true
}
]
},
showInlineValues: true,
centeredInllineValues: true,
label: {
font: {
family: "Georgia"
}
}
};
var priceBarChart = new Chart(ctxBarChart, {
type: 'horizontalBar',
data: barChartData,
options: optionsBar
});
priceBarChart.defaults.global.defaultFont = "Georgia";
更新
Dekel:你的答案非常接近——这就是我在代码不变的情况下看到的:
因此,不仅放置在栏上的值需要更靠右,我还需要像以前一样显示悬停数据(现在它被截断了一点,正如你在屏幕截图中看到的那样),而不是两个值在条形图的每个段上显示一个 % 值(这两个值中较大的 % 是两个数字的组合值)。
注意:这同样适用于另一个问题(事实上,只要我还有积分,我的所有问题):我将奖励他们允许的最大积分数(500)。
更新 2
通过更改此代码:
ctx.fillText(dataset.data[i], model.base + 10, model.y + 5);
...对此:
ctx.fillText("99.9%", model.base + 25, model.y + 6);
...我现在看到条上的数字右对齐(但是,当然,它们都是虚假/模拟值)。不过,悬停值仍然被截断,我不需要在每个条的末尾重复该值(“99.9%”)。