我正在创建一个像这样的条形图:
var ctxForecastChart = $("#forecastLineChart").get(0).getContext("2d");
var forecastChartData = {
labels: [
"Total Sales"
],
datasets: [
{
label: "8/28/2016 - 9/3/2016",
backgroundColor: "rgba(255,0,0,0.75)",
hoverBackgroundColor: "rgba(255,0,0,1)",
data: [240]
},
{
label: "9/25/2016 - 10/2/2016",
backgroundColor: "rgba(255,153,0,0.75)",
hoverBackgroundColor: "rgba(255,153,0,1)",
data: [272]
},
{
label: "9/18/2016 - 9/24/2016",
backgroundColor: "rgba(255,255,0,0.75)",
hoverBackgroundColor: "rgba(255,255,0,1)",
data: [250]
},
{
label: "9/4/2016 - 9/10/2016",
backgroundColor: "rgba(0,255,0,0.75)",
hoverBackgroundColor: "rgba(0,255,0,1)",
data: [232]
},
{
label: "9/11/2016 - 9/17/2016",
backgroundColor: "rgba(0,0,255,0.75)",
hoverBackgroundColor: "rgba(0,0,255,1)",
data: [244]
}]
};
var forecastOptions = {
tooltips: {
enabled: true
}
};
var forecastBarChart = new Chart(ctxForecastChart,
{
type: 'bar',
data: forecastChartData,
options: forecastOptions
});
这看起来像这样:
我想要做的是在最后一个栏(蓝色的)上方添加一个标签,在前一个/第四个和那个之间有一个百分比差异。在这种情况下,该值应为“+5.2%”,使其如下所示:
我认为这将需要注册 afterDraw() 事件,但它应该是什么样子的细节超出了我的范围。
更新
如果我将此添加到建议的代码中:
if (chartInstance.id !== 2) return; // affect this one only
在上下文中:
afterDraw: function (chartInstance) {
if (chartInstance.id !== 2) return; // affect this one only
// We get the canvas context
var ctx = chartInstance.chart.ctx;
...结果比没有它要好一些(它破坏了我的第一个(饼图)图表并完全消除了接下来的两个(包括这里讨论的那个):
正如你所看到的,饼图仍然被冲洗,两个条形图中的值被缩小了,就好像一个食人部落对它们实施了邪恶的把戏。而且,在最后一个条形顶部没有任何附加值。