我正在开发一个使用条形图的网站,我无法找到自定义条形图的方法,以便在每个条形图上显示值。
这是我的条形图js
$(function(){
var t;
function size(animate){
if (animate == undefined){
animate = false;
}
clearTimeout(t);
t = setTimeout(function(){
$("#bar-chart-js").each(function(i,el){
$(el).attr({
"width":$(el).parent().width(),
"height":$(el).parent().outerHeight()
});
});
redraw(animate);
var m = 0;
$(".chartJS").height("");
$(".chartJS").each(function(i,el){ m = Math.max(m,$(el).height()); });
$(".chartJS").height(m);
}, 30);
}
$(window).on('resize', function(){ size(false); });
function redraw(animation){
var options = {};
if (!animation){
options.animation = true;
} else {
options.animation = true;
}
var dataJson1 = <?php echo json_encode($monthly_income);?>;
var dataJson2 = <?php echo json_encode($monthly_expense);?>;
var data1 = $.map(dataJson1, function(el) { return el; });
var data2 = $.map(dataJson2, function(el) { return el; });
//console.log(dataJson1);
//console.log('data1:' + data1);
var barChartData = {
labels : ["January","February","March","April","May","June","July","August","September","October","November","December"],
datasets : [
{
fillColor : "#79D1CF",
strokeColor : "#79D1CF",
data : data1
},
{
fillColor : "#E67A77",
strokeColor : "#E67A77",
data : data2
}
]
};
var myLine = new Chart(document.getElementById("bar-chart-js").getContext("2d")).Bar(barChartData);
}
size(true);
});
我想将索引标签显示为下面的图像
请帮助我,我非常感谢您的帮助。
答案 0 :(得分:1)
只需在animationComplete回调中添加标签
即可var myLine = new Chart(document.getElementById("bar-chart-js").getContext("2d")).Bar(barChartData, {
showTooltips: false,
onAnimationComplete: function () {
var ctx = this.chart.ctx;
ctx.font = this.scale.font;
ctx.fillStyle = this.scale.textColor
ctx.textAlign = "center";
ctx.textBaseline = "bottom";
this.datasets.forEach(function (dataset) {
dataset.bars.forEach(function (bar) {
ctx.fillText(bar.value, bar.x, bar.y);
});
})
}
});
我已经关闭了工具提示,假设您不再需要它们(因为新添加的标签中显示的信息相同)。如果需要工具提示,则需要扩展条形图并在每次绘制图表后将上述逻辑移至。
小提琴 - http://jsfiddle.net/geaje18p/(我用硬编码数组取代了你的php回声)