I'm using chart.Js to display my chart. I'm getting my chart data via ajax and graphically render it to display the data,
My question is, there are few cases when my Ajax returns nothing, and my Chart just display X axis and Y axis, with no data or no legend shown. Is there any option to show default text ?
PS: I know I can add some conditional statement and display "No chart Div" and hide my "chart div", but i was some clean method to do the same.
You can try this solution:
if(1 < chartData.labels.length) {
chart = new Chart(options.ctx).Line(chartData, options.chartOptions);
} else {
options.ctx.font = "20px " + Chart.defaults.global.tooltipTitleFontFamily;
options.ctx.textAlign = "center";
options.ctx.textBaseline = "middle";
options.ctx.fillStyle = Chart.defaults.global.scaleFontColor;
options.ctx.fillText("No data in chart.", options.ctx.canvas.clientWidth / 2, options.ctx.canvas.clientHeight / 2);
}
This works for me I hope it helps
Chart.pluginService.register({
afterDraw: function (chart) {
if (chart.data.datasets[0].data.length === 0) {
// No data is present
var ctx = chart.chart.ctx;
var width = chart.chart.width;
var height = chart.chart.height
chart.clear();
ctx.save();
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.font = "20px normal 'Helvetica Nueue'";
ctx.fillText('No data to display', width / 2, height / 2);
ctx.restore();
}
}
});
Related
I'm using a permutation of #Cmyker's code (see here) to have text in the center of a doughnut chart, but I'm having trouble getting the date setting I made to break into another line instead of sticking to the same line as the rest of the text. I've tried adding /n on the end of the text where I want it to break but that doesn't seem to be working, any advice on this?
//Date for chart
let today = new Date();
var date = today.getDate()+'/'+(today.getMonth()+1)+'/'+today.getFullYear();
//Chart
window.onload = function(){
//dataset
var data = {
labels: [" Akaun 1"," Akaun 2"],
datasets: [{
data: [1300.00, 895.75],
backgroundColor: ["#430092","#36A2EB"],
hoverBackgroundColor: ["#430092","#36A2EB"],
cutout: ["70%"],
}]
};
//init & config
var chart = new Chart(document.getElementById('myChart'), {
type: 'doughnut',
data: data,
options: {
responsive: true,
legend: { display: false},
labels: { font: {size: 12}}
}
});
const centerDoughnutPlugin = {
id: "annotateDoughnutCenter",
beforeDraw: (chart) => {
let width = chart.chartArea.left + chart.chartArea.right;
let height = chart.chartArea.top + chart.chartArea.bottom;
let ctx = chart.ctx;
ctx.restore();
//Font setting
let fontSize = (height / 250).toFixed(2);
ctx.font = fontSize + "em sans-serif";
ctx.textBaseline = "middle";
ctx.textAlign = "center";
let text = "Balance as of: \n" + date;
//Center text
let textX = width / 2;
let textY = height / 2;
console.log("text x: ", textX);
console.log("text y: ", textY);
ctx.fillText(text, textX, textY);
ctx.save();
},
};
Chart.register(centerDoughnutPlugin);
}
<canvas id="myChart">
</canvas>
CanvasRenderingContext2D.fillText() draws text in a single line. If you need to break it into multiple lines, you'll need to split the text and invoke filltext() multiple times.
As an alternative you may use the Canvas-Txt library.
Please take a look at this answer https://stackoverflow.com/a/54390661/2358409
I would like to make a doughnut chart using Chart.Js library, with text in the center of the doughnut and the percentage on each segment.
The segments on the chart are generated dynamically.
So I look through Stackoverflow to look for solution, and combined 2 that I found:
How to create a donut chart like this in chart.js
How to add text inside the doughnut chart using Chart.js?
and combine into the following javascript:
Chart.defaults.derivedDoughnut = Chart.defaults.doughnut;
var helpers = Chart.helpers;
var customDN = Chart.controllers.doughnut.extend({
draw: function(ease) {
Chart.controllers.doughnut.prototype.draw.call(this, ease);
if (this.chart.config.options.elements.center) {
//Get ctx from string
var ctx = this.chart.chart.ctx;
//Get options from the center object in options
var centerConfig = this.chart.config.options.elements.center;
var fontStyle = centerConfig.fontStyle || 'Arial';
var txt = centerConfig.text;
var color = centerConfig.color || '#000';
var sidePadding = centerConfig.sidePadding || 20;
var sidePaddingCalculated = (sidePadding/100) * (this.chart.innerRadius * 2)
//Start with a base font of 30px
ctx.font = "30px " + fontStyle;
//Get the width of the string and also the width of the element minus 10 to give it 5px side padding
var stringWidth = ctx.measureText(txt).width;
var elementWidth = (this.chart.innerRadius * 2) - sidePaddingCalculated;
// Find out how much the font can grow in width.
var widthRatio = elementWidth / stringWidth;
var newFontSize = Math.floor(20 * widthRatio);
var elementHeight = (this.chart.innerRadius * 2);
// Pick a new font size so it will not be larger than the height of label.
var fontSizeToUse = Math.min(newFontSize, elementHeight);
//Set font settings to draw it correctly.
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
var centerX = ((this.chart.chartArea.left + this.chart.chartArea.right) / 2);
var centerY = ((this.chart.chartArea.top + this.chart.chartArea.bottom) / 2);
ctx.font = fontSizeToUse+"px " + fontStyle;
ctx.fillStyle = color;
//Draw text in center
ctx.fillText(txt, centerX, centerY);
//labels
var chart = this.chart;
var chartArea = chart.chartArea;
var opts = chart.options;
var meta = this.getMeta();
var arcs = meta.data;
for (i in arcs){
var arcctx = arcs[i]._chart.ctx;
var view = arcs[i]._view;
var sa = view.startAngle;
var ea = view.endAngle;
var opts = arcs[i]._chart.config.options;
var labelPos = arcs[i].tooltipPosition();
var segmentLabel = view.circumference / opts.circumference*100;
arcctx.fillStyle = view.borderColor;
arcctx.font = "1px" + fontStyle;
arcctx.fillText(segmentLabel.toFixed(0) + "%", labelPos.x, labelPos.y);
}
}
}
});
but my outcome is outcome image
I tried fixing the font of the arc, but it still does not work. It seems to utilize the font set for the text in the center of the doughnut.
Can someone tell me what did I do wrong here, how do I set the font size of the arc and text in the center of the doughnut differently? Thanks!
Is there a good way to remove duplicate data labels in Chartjs? Or a good way to space labels out better above data points so they are not on top of each other?
Chart.plugins.register({
afterDatasetsDraw: function(chart, easing) {
// To only draw at the end of animation, check for easing === 1
var ctx = chart.ctx;
chart.data.datasets.forEach(function (dataset, i) {
var meta = chart.getDatasetMeta(i);
if (!meta.hidden) {
meta.data.forEach(function(element, index) {
// Draw the text in black, with the specified font
ctx.fillStyle = 'rgb(255, 255, 255)';
var fontSize = 12;
var fontStyle = 'normal';
var fontFamily = 'Arial';
ctx.font = Chart.helpers.fontString(fontSize, fontStyle, fontFamily);
// Just naively convert to string for now
var dataString = dataset.data[index].toString();
// Make sure alignment settings are correct
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
var bodySpacing = 3;
var padding = 10;
var position = element.tooltipPosition();
ctx.fillText(dataString, position.x, position.y - (fontSize / 2) - padding);
});
}
});
}
});
To clarify, the data is my data. The code is taken from the chartjs sample data labeling page and basically pasted in.
Visit this chart Style in chart.js library. It show list of all data on specific point. Here is link
I'm using jquery.flot.barnumbers.js plugin for the Javascript plotting (charts) library for jQuery to show the numbers on the bars.
My code:
$.plot("#placeholderByDay", [
{
data: DataOne, label: "Total Calls", bars: {
numbers:{
show:true,
xAlign: 80,//align top
yAlign: 1
//yAlign: function(y) { return y+ 1; } //upside of bars
}
} ]);
What I get now is:
What I need is:
So when there is no data for a bar, the zeros should be just above the axis, and where there are values should be as is, both rotated let 90 degrees. How can I achieve this?
Oops, I did it again.
If you'd like to drop the plugin and do this the fun way; code it up yourself. It'll give you the freedom to customize any way you like.
// after you draw the plot
var ctx = somePlot.getCanvas().getContext("2d");
var data = somePlot.getData()[0].data;
var xaxis = somePlot.getXAxes()[0];
var yaxis = somePlot.getYAxes()[0];
var offset = somePlot.getPlotOffset();
ctx.font = "16px 'Segoe UI'";
ctx.fillStyle = "black";
for (var i = 0; i < data.length; i++){
var text = data[i][4] + '';
var metrics = ctx.measureText(text);
var xPos = xaxis.p2c(data[i][0]) + offset.left;
var yPos = yaxis.p2c(data[i][5]) + offset.top + metrics.width + 5;
// perform the rotation
ctx.save();
ctx.translate(xPos, yPos);
ctx.rotate(-Math.PI/2);
ctx.fillText(text, 1, 1);
ctx.restore();
}
Example here.
part of the plot
I use "categories" in yaxis,the y position of the text should be like that:
for(var i=0;i<data1.length;i++){
.....
var yPos = yaxis.p2c(i) + fontSize;
.....
}
if you want the flot shows like that:
the y position of the text should be like that:
for(var i=0;i<data1.length;i++){
.....
var yPos = yaxis.p2c(i+align) + fontSize;
.....
}
align = barWidth/2, if bars' align = 'left';
align = -barWidth/2, if bars' align = 'right;
I'm using jquery.flot.barnumbers.js plugin for the Javascript plotting (charts) library for jQuery to show the numbers on the bars.
My code:
$.plot("#placeholderByDay", [
{
data: DataOne, label: "Total Calls", bars: {
numbers:{
show:true,
xAlign: 80,//align top
yAlign: 1
//yAlign: function(y) { return y+ 1; } //upside of bars
}
} ]);
What I get now is:
What I need is:
So when there is no data for a bar, the zeros should be just above the axis, and where there are values should be as is, both rotated let 90 degrees. How can I achieve this?
Oops, I did it again.
If you'd like to drop the plugin and do this the fun way; code it up yourself. It'll give you the freedom to customize any way you like.
// after you draw the plot
var ctx = somePlot.getCanvas().getContext("2d");
var data = somePlot.getData()[0].data;
var xaxis = somePlot.getXAxes()[0];
var yaxis = somePlot.getYAxes()[0];
var offset = somePlot.getPlotOffset();
ctx.font = "16px 'Segoe UI'";
ctx.fillStyle = "black";
for (var i = 0; i < data.length; i++){
var text = data[i][4] + '';
var metrics = ctx.measureText(text);
var xPos = xaxis.p2c(data[i][0]) + offset.left;
var yPos = yaxis.p2c(data[i][5]) + offset.top + metrics.width + 5;
// perform the rotation
ctx.save();
ctx.translate(xPos, yPos);
ctx.rotate(-Math.PI/2);
ctx.fillText(text, 1, 1);
ctx.restore();
}
Example here.
part of the plot
I use "categories" in yaxis,the y position of the text should be like that:
for(var i=0;i<data1.length;i++){
.....
var yPos = yaxis.p2c(i) + fontSize;
.....
}
if you want the flot shows like that:
the y position of the text should be like that:
for(var i=0;i<data1.length;i++){
.....
var yPos = yaxis.p2c(i+align) + fontSize;
.....
}
align = barWidth/2, if bars' align = 'left';
align = -barWidth/2, if bars' align = 'right;