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 am using amcharts to render a simple pie chart and I would like the pie chart to start on the left most edge of the container.
I have gone through the amcharts API but nothing seems to do what I need.
Below you can see the code I am using and an image of what I get (With some red lines drawn on of what I want
am4core.useTheme(am4themes_animated);
// Themes end
var data = [
{
revenueSource: "Fee Revenue",
value: 356
},
{
revenueSource: "Retail Revenue",
value: 247
},
{
revenueSource: "Ticket Revenue",
value: 9876
}
];
var chart1 = am4core.create("chartdiv", am4charts.PieChart);
chart1.hiddenState.properties.opacity = 0;
chart1.data = data;
chart1.innerRadius = am4core.percent(50);
chart1.legend = new am4charts.Legend();
chart1.legend.position = "right";
var series1 = chart1.series.push(new am4charts.PieSeries());
series1.dataFields.value = "value";
series1.dataFields.category = "revenueSource";
series1.ticks.template.disabled = true;
series1.labels.template.disabled = true;
Note. The div that the chart renders within has a height of 400px and a width of 100%
chart1.seriesContainer.align = "left";
Should do the job.
I have a doughnut chart using Chart.js that displays login data for my app correctly, however I have modified the chart so that the total number of logins is displayed in text in the center cutout:
The problem I am running into is with the tooltips. When I hover over the light teal piece of the pie chart, if the chart is scaled smaller, the tooltip is overlapped by the text in the center, like this:
I want to be able to change the direction the tooltip extends out, so instead of it going towards the center, it moves away so that both the tooltip and the center analytic are visible, but I have yet to find a concise explanation on how to change tooltip positioning. Here is the code I have currently:
var loslogged = dataset[0][0].loslogged;
var realtorlogged = dataset[1][0].realtorlogged;
var borrowerlogged = dataset[2][0].borrowerlogged;
var totallogged = parseInt(loslogged) + parseInt(realtorlogged) + parseInt(borrowerlogged);
Chart.pluginService.register({
afterDraw: function (chart) {
if (chart.config.options.elements.center) {
var helpers = Chart.helpers;
var centerX = (chart.chartArea.left + chart.chartArea.right) / 2;
var centerY = (chart.chartArea.top + chart.chartArea.bottom) / 2;
var ctx = chart.chart.ctx;
ctx.save();
var fontSize = helpers.getValueOrDefault(chart.config.options.elements.center.fontSize, Chart.defaults.global.defaultFontSize);
var fontStyle = helpers.getValueOrDefault(chart.config.options.elements.center.fontStyle, Chart.defaults.global.defaultFontStyle);
var fontFamily = helpers.getValueOrDefault(chart.config.options.elements.center.fontFamily, Chart.defaults.global.defaultFontFamily);
var font = helpers.fontString(fontSize, fontStyle, fontFamily);
ctx.font = font;
ctx.fillStyle = helpers.getValueOrDefault(chart.config.options.elements.center.fontColor, Chart.defaults.global.defaultFontColor);
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(chart.config.options.elements.center.text, centerX, centerY);
ctx.restore();
}
}
});
var loginChartData = {
labels: ["Loan Officers","Realtors","Borrowers"],
datasets: [{
label: "Number of Logins",
data: [loslogged, realtorlogged, borrowerlogged],
backgroundColor: [
"rgba(191, 25, 25, 0.75)",
"rgba(58, 73, 208, 0.75)",
"rgba(79, 201, 188, 0.75)"
],
borderColor: [
"rgba(255, 255, 255, 1)",
"rgba(255, 255, 255, 1)",
"rgba(255, 255, 255, 1)"
],
borderWidth: 4
}],
gridLines: {
display: false
}
};
var loginChartOptions = {
title: {
display: false
},
cutoutPercentage: 50,
elements: {
center: {
text: totallogged,
fontColor: '#000',
fontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
fontSize: 36,
fontStyle: 'bold'
}
}
};
var loginChart = document.getElementById('loginsChart').getContext('2d');
new Chart(loginChart, {
type: 'doughnut',
data: loginChartData,
options: loginChartOptions
});
It used to be a lot easier to reverse the tooltips in previous versions of chart.js (v2.3 and before). All you had to do was overwrite the determineAlignment tooltip method and reverse the logic.
However starting in v2.4, the functions that calculate the tooltip positions (including determineAlignment) were made private, so there is no longer a way to simply overwrite them (instead you have to duplicate them).
Here is a working reversed tooltip solution that unfortunately requires a lot of copy and paste from the chart.js source (this is required since the methods are private). The risk with this approach is that the underlying private functions could change in new releases at any time and your new reverse tooltip could break unexpectedly.
With that said, here is walk through of the implementation (with a codepen example at the bottom).
1) First, let's extend the Chart.Tooltip object and create a new Chart.ReversedTooltip object. We really only need to overwrite the update method since it performs all the positioning logic. In fact, this overwrite is just a straight copy and paste from the source because we actually only need to modify the private determineAlignment method which is called by update.
// create a new reversed tooltip. we must overwrite the update method which is
// where all the positioning occurs
Chart.ReversedTooltip = Chart.Tooltip.extend({
update: function(changed) {
var me = this;
var opts = me._options;
// Need to regenerate the model because its faster than using extend and it is necessary due to the optimization in Chart.Element.transition
// that does _view = _model if ease === 1. This causes the 2nd tooltip update to set properties in both the view and model at the same time
// which breaks any animations.
var existingModel = me._model;
var model = me._model = getBaseModel(opts);
var active = me._active;
var data = me._data;
var chartInstance = me._chartInstance;
// In the case where active.length === 0 we need to keep these at existing values for good animations
var alignment = {
xAlign: existingModel.xAlign,
yAlign: existingModel.yAlign
};
var backgroundPoint = {
x: existingModel.x,
y: existingModel.y
};
var tooltipSize = {
width: existingModel.width,
height: existingModel.height
};
var tooltipPosition = {
x: existingModel.caretX,
y: existingModel.caretY
};
var i, len;
if (active.length) {
model.opacity = 1;
var labelColors = [];
tooltipPosition = Chart.Tooltip.positioners[opts.position](active, me._eventPosition);
var tooltipItems = [];
for (i = 0, len = active.length; i < len; ++i) {
tooltipItems.push(createTooltipItem(active[i]));
}
// If the user provided a filter function, use it to modify the tooltip items
if (opts.filter) {
tooltipItems = tooltipItems.filter(function(a) {
return opts.filter(a, data);
});
}
// If the user provided a sorting function, use it to modify the tooltip items
if (opts.itemSort) {
tooltipItems = tooltipItems.sort(function(a, b) {
return opts.itemSort(a, b, data);
});
}
// Determine colors for boxes
helpers.each(tooltipItems, function(tooltipItem) {
labelColors.push(opts.callbacks.labelColor.call(me, tooltipItem, chartInstance));
});
// Build the Text Lines
model.title = me.getTitle(tooltipItems, data);
model.beforeBody = me.getBeforeBody(tooltipItems, data);
model.body = me.getBody(tooltipItems, data);
model.afterBody = me.getAfterBody(tooltipItems, data);
model.footer = me.getFooter(tooltipItems, data);
// Initial positioning and colors
model.x = Math.round(tooltipPosition.x);
model.y = Math.round(tooltipPosition.y);
model.caretPadding = helpers.getValueOrDefault(tooltipPosition.padding, 2);
model.labelColors = labelColors;
// data points
model.dataPoints = tooltipItems;
// We need to determine alignment of the tooltip
tooltipSize = getTooltipSize(this, model);
alignment = determineAlignment(this, tooltipSize);
// Final Size and Position
backgroundPoint = getBackgroundPoint(model, tooltipSize, alignment);
} else {
model.opacity = 0;
}
model.xAlign = alignment.xAlign;
model.yAlign = alignment.yAlign;
model.x = backgroundPoint.x;
model.y = backgroundPoint.y;
model.width = tooltipSize.width;
model.height = tooltipSize.height;
// Point where the caret on the tooltip points to
model.caretX = tooltipPosition.x;
model.caretY = tooltipPosition.y;
me._model = model;
if (changed && opts.custom) {
opts.custom.call(me, model);
}
return me;
},
});
2) As you can see, the update method uses a handful of private methods (e.g. getBaseModel, createTooltipItem, determineAlignment, etc.). In order for our update method to actually work, we have to provide an implementation for each of these methods. Here again is another copy and paste from the source. The only method that we need to modify however is the determineAlignment method. Here is the modified version that reverses the alignment logic.
// modified from source to reverse the position
function determineAlignment(tooltip, size) {
var model = tooltip._model;
var chart = tooltip._chart;
var chartArea = tooltip._chartInstance.chartArea;
var xAlign = 'center';
var yAlign = 'center';
// set caret position to top or bottom if tooltip y position will extend outsite the chart top/bottom
if (model.y < size.height) {
yAlign = 'top';
} else if (model.y > (chart.height - size.height)) {
yAlign = 'bottom';
}
var leftAlign, rightAlign; // functions to determine left, right alignment
var overflowLeft, overflowRight; // functions to determine if left/right alignment causes tooltip to go outside chart
var yAlign; // function to get the y alignment if the tooltip goes outside of the left or right edges
var midX = (chartArea.left + chartArea.right) / 2;
var midY = (chartArea.top + chartArea.bottom) / 2;
if (yAlign === 'center') {
leftAlign = function(x) {
return x >= midX;
};
rightAlign = function(x) {
return x < midX;
};
} else {
leftAlign = function(x) {
return x <= (size.width / 2);
};
rightAlign = function(x) {
return x >= (chart.width - (size.width / 2));
};
}
overflowLeft = function(x) {
return x - size.width < 0;
};
overflowRight = function(x) {
return x + size.width > chart.width;
};
yAlign = function(y) {
return y <= midY ? 'bottom' : 'top';
};
if (leftAlign(model.x)) {
xAlign = 'left';
// Is tooltip too wide and goes over the right side of the chart.?
if (overflowLeft(model.x)) {
xAlign = 'center';
yAlign = yAlign(model.y);
}
} else if (rightAlign(model.x)) {
xAlign = 'right';
// Is tooltip too wide and goes outside left edge of canvas?
if (overflowRight(model.x)) {
xAlign = 'center';
yAlign = yAlign(model.y);
}
}
var opts = tooltip._options;
return {
xAlign: opts.xAlign ? opts.xAlign : xAlign,
yAlign: opts.yAlign ? opts.yAlign : yAlign
};
};
3) Now that our new Chart.ReversedTooltip is complete, we need to use the plugin system to change the original tooltip to our reversed tooltip. We can do this using the afterInit plugin method.
Chart.plugins.register({
afterInit: function (chartInstance) {
// replace the original tooltip with the reversed tooltip
chartInstance.tooltip = new Chart.ReversedTooltip({
_chart: chartInstance.chart,
_chartInstance: chartInstance,
_data: chartInstance.data,
_options: chartInstance.options.tooltips
}, chartInstance);
chartInstance.tooltip.initialize();
}
});
After all that, we finally have reversed tooltips! Checkout a full working example at this codepen.
It's also worth mentioning that this approach is very brittle and, as I mentioned, can easily break overtime (on account of the copy and pasting required). Another option would be to just use a custom tooltip instead and position it wherever you desire on the chart.
Checkout this chart.js sample that shows how to setup and use a custom tooltip. You could go with this approach and just modify the positioning logic.
If you have a small tooltip label, you can use simple chart.js options to fix overlaps issue:
plugins: {
tooltip: {
xAlign: 'center',
yAlign: 'bottom'
}
}
I managed to solve the same by setting zIndex of Doughnut wrapper div to 1, settting the zIndex of text shown in the middle of Doughnut to -1, and canvas is transparent by default.
Hope this hels.
I'm building an interactive widget using Google Charts.
For now, got a pie chart and a scatterplot as you can see bellow.
Although, would like to have in the scatterplot a pie chart instead of the blue tiny dot (can even be an image.
Any idea in how to do this?
Spend 4 hours doing research and didn't find anything that would let me do it.
Some debug?
SCRIPT
<script src="https://www.gstatic.com/charts/loader.js"></script>
////Callback that draws the scatter
function draw0RiskChart() {
var data = google.visualization.arrayToDataTable([
['Risk in %', 'Return in %'],
[ 9.87, 6.53]
]);
var options = {
title: 'Risk vs. Return with 0% Hedge Fund',
hAxis: {title: 'Risk', minValue: 5, maxValue: 10},
vAxis: {title: 'Return', minValue: 5, maxValue: 10},
width:400,
height:300
};
var container = new google.visualization.ScatterChart(document.getElementById('0risk_chart_div'));
var chart = new google.visualization.ScatterChart(container);
// Wait for the chart to finish drawing before calling the getImageURI() method.
google.visualization.events.addListener(chart, 'ready', function () {
var layout = chart.getChartLayoutInterface();
container.innerHTML = '<img src="' + chart.getImageURI() + '">';
for (var i = 0; i < data.getNumberOfRows(); i++) {
// add image above in every element
var xPos = layout.getXLocation(data.getValue(i, 0));
var yPos = layout.getYLocation(data.getValue(i, 1));
var whiteHat = container.appendChild(document.createElement('img'));
whiteHat.src = 'http://findicons.com/files/icons/512/star_wars/16/clone_old.png';
whiteHat.className = 'whiteHat';
// 16x16 (image size in this example)
whiteHat.style.top = (yPos - 16) + 'px';
whiteHat.style.left = (xPos) + 'px';
}
console.log(container.innerHTML);
});
chart.draw(data, options);
}
STYLE
.whiteHat {
border: none;
position: absolute;
}
BODY
<div id="0risk_chart_div"></div>
I am using chart.js for drawing doughnut chart. Using 'fillText' I am adding text at the middle part of doughnut chart.But how i can give a background color for the middle
here is my code
javascript
<script>
var doughnutData = [
{
value: 300,
color:"#F7464A",
highlight: "#FF5A5E",
label: "Red"
},
{
value: 50,
color: "#46BFBD",
highlight: "#5AD3D1",
label: "Green"
},
{
value: 100,
color: "#FDB45C",
highlight: "#FFC870",
label: "Yellow"
},
{
value: 40,
color: "#949FB1",
highlight: "#A8B3C5",
label: "Grey"
},
{
value: 120,
color: "#4D5360",
highlight: "#616774",
label: "Dark Grey"
}
];
window.onload = function(){
var ctx = document.getElementById("chart-area").getContext("2d");
var option =
{
//prevents the text vanishing on redraw (when tooltip shows on hover)
showTooltips: false,
//nicer than default bouncing
animationEasing: "easeOut",
//bit smoother with less steps
animationSteps: 40,
//do once on completion rather than every frame/draw cycle
onAnimationComplete: function () {
//setup the font and center it's position
this.chart.ctx.font = 'Normal 18px Ariel';
this.chart.ctx.textAlign = 'center';
this.chart.ctx.textBaseline = 'middle';
//put the pabel together based on the given 'skilled' percentage
var valueLabel = this.segments[0].value + '%';
//find the center point
var x = this.chart.canvas.clientWidth / 2;
var y = this.chart.canvas.clientHeight / 2;
//hack to center different fonts
var x_fix = 0;
var y_fix = 2;
//render the text
this.chart.ctx.fillText("Text", x + x_fix, y + y_fix);
this.chart.ctx.fillStyle("red");
//this.chart.ctx.fill();
}
};
window.myDoughnut = new Chart(ctx).Doughnut(doughnutData,option, {responsive : true});
};
</script>
HTML
<div id="canvas-holder">
<canvas id="chart-area" width="300" height="300"/>
</div>
chart.js has to include
only for the middle I have to add background color. (for 'text' i have to add background color)
I have tried with this.chart.ctx.fillStyle("red"); and this.chart.ctx.fillStyle("red", x + x_fix, y + y_fix); but both not working
thank you
After 2 hours I got the answer
add the circle code before adding the text
this.chart.ctx.beginPath();
this.chart.ctx.arc(x,y,80,0,2*Math.PI);
this.chart.ctx.fillStyle = '#8AC007';
this.chart.ctx.fill();
this.chart.ctx.lineWidth = 5;
this.chart.ctx.strokeStyle = '#003300';
this.chart.ctx.stroke();
this.chart.ctx.fillStyle = 'blue';
this.chart.ctx.fillText("Text", x + x_fix, y + y_fix);
result will be like above image