How to customize chart js Bar chart shape? - javascript

How can I change Chart Js's bar chart shape to have pointy top and bottom like this picture?

One way to get the triangles is to do a stacked chart, and add a line graph on top. To keep it reactive you would need to dynamically resize the pointRadius on the line data.
https://jsfiddle.net/0mcd5s13/3/
Or on line 4640 of chart.js you can change element_rectangle draw function to this:
draw: function() {
var ctx = this._chart.ctx;
var vm = this._view;
var rects = boundingRects(vm);
var outer = rects.outer;
var inner = rects.inner;
//ctx.fillStyle = vm.backgroundColor;
//ctx.fillRect(outer.x, outer.y, outer.w, outer.h);
if (outer.w === inner.w && outer.h === inner.h) {
return;
}
let offset = outer.w / 2;
ctx.save();
ctx.beginPath();
ctx.moveTo(outer.x, outer.y);
ctx.lineTo(outer.x, outer.y + outer.h);
ctx.lineTo(outer.x + offset, outer.y + outer.h + offset);
//ctx.lineTo(outer.x + offset, outer.y + outer.h);
ctx.lineTo(outer.x + outer.w, outer.y + outer.h);
ctx.lineTo(outer.x + outer.w, outer.y);
ctx.lineTo(outer.x + offset, outer.y - offset);
ctx.lineTo(outer.x, outer.y);
ctx.stroke();
//ctx.rect(outer.x, outer.y, outer.w, outer.h);
ctx.clip();
ctx.fillStyle = vm.borderColor;
// ctx.rect(inner.x, inner.y, inner.w, inner.h);
ctx.fill('evenodd');
ctx.restore();
},
which yields this:
more likely to import chart.js from a source, you will need make your own type of chart as an extension of bar chart.
(function(Chart) {
var helpers = Chart.helpers;
Chart.defaults.triBar = {
hover: {
mode: "label"
},
dataset: {
categoryPercentage: 0.8,
barPercentage: 0.9
},
scales: {
xAxes: [{
type: "category",
// grid line settings
gridLines: {
offsetGridLines: true
}
}],
yAxes: [{
type: "linear"
}]
}
};
Chart.controllers.triangleBar = Chart.controllers.bar.extend({
//
// extend element_rectangle draw function here
//
});
}).call(this, Chart);

Related

Is it possible to sync zoom between two scatter highcharts?

I want to achieve two things.
1 - In the above image, imagine that the top part does not exist to begin with. If the user were to click on any point on the bottom chart, I want the top chart to be created with a magnified view. And if the bottom part is clicked and dragged, the top part should follow that.
2 - If the bottom chart were zoomed in, I want the top chart to also be zoomed in. Ex: If bottom was 1x and top was 2x, if I zoom bottom by 2x, top should now be 4x.
Are these possible with highcharts?
Yes, that behavior is easily achievable in Highcharts. All you need to do is to use Axis.afterSetExtremes and Point.click event callback function to create or update another chart with proper axis extremes. For example:
var chart1,
scale = 4;
function createOrUpdateDetail() {
var isPointClick = !this.lin2log,
chart = this.chart || this.series.chart,
xMin = chart.xAxis[0].min,
xMax = chart.xAxis[0].max,
xRange = xMax - xMin,
xCenter = (xMax + xMin) / 2,
yMin = chart.yAxis[0].min,
yMax = chart.yAxis[0].max,
yRange = yMax - yMin,
yCenter = (yMax + yMin) / 2,
calcXMin,
calcXMax,
calcYMin,
calcYMax;
if (isPointClick) {
xCenter = this.x;
yCenter = this.y;
}
calcXMin = xCenter - xRange / scale;
calcXMax = xCenter + xRange / scale;
calcYMin = yCenter - yRange / scale;
calcYMax = yCenter + yRange / scale;
if (!chart1) {
chart1 = Highcharts.chart('container', {
series: [{
type: 'scatter',
data: this.series.options.data
}],
xAxis: {
min: calcXMin,
max: calcXMax,
},
yAxis: {
endOnTick: false,
startOnTick: false,
min: calcYMin,
max: calcYMax
}
});
} else {
chart1.update({
xAxis: {
min: calcXMin,
max: calcXMax,
},
yAxis: {
min: calcYMin,
max: calcYMax
}
});
}
}
Highcharts.chart('container2', {
chart: {
zoomType: 'xy',
panning: true,
panKey: 'shift'
},
yAxis: {
endOnTick: false,
startOnTick: false,
},
xAxis: {
events: {
afterSetExtremes: createOrUpdateDetail
}
},
series: [{
type: 'scatter',
data: [...],
point: {
events: {
click: createOrUpdateDetail
}
}
}]
});
Live demo: http://jsfiddle.net/BlackLabel/6m4e8x0y/4982/
API Reference:
https://api.highcharts.com/highcharts/xAxis.events.afterSetExtremes
https://api.highcharts.com/highcharts/series.scatter.events.click
https://api.highcharts.com/class-reference/Highcharts.Chart#update

Chart.js - Horizontal line on Bar chart interferes with tooltip

I'm using Chart.js 2.6 and I have implemented the horizontalLine plugin to show an average value on my bar charts. It works fine, however when the tooltip displays in the spot where it intersects with the line, it is partially covered by the horizontal line itself. I'm trying to figure out how to make the tooltip draw ABOVE the horizontal line.
I understand the tooltip is part of the canvas element, and therefore does not have a z-index property. How can I accomplish this?
Here is what I'm using for my horizontal line plugin.
var horizonalLinePlugin = {
afterDraw: function(chartInstance) {
var yScale = chartInstance.scales["y-axis-0"];
var canvas = chartInstance.chart;
var ctx = canvas.ctx;
var index, line, style, width;
if (chartInstance.options.horizontalLine) {
for (index = 0; index < chartInstance.options.horizontalLine.length; index++) {
line = chartInstance.options.horizontalLine[index];
style = (line.style) ? line.style : "rgba(169,169,169, .6)";
yValue = (line.y) ? yScale.getPixelForValue(line.y) : 0 ;
ctx.lineWidth = (line.width) ? line.width : 3;
if (yValue) {
ctx.beginPath();
ctx.moveTo(chartInstance.chartArea.left, yValue);
ctx.lineTo(canvas.width, yValue);
ctx.strokeStyle = style;
ctx.stroke();
}
if (line.text) {
ctx.fillStyle = style;
ctx.fillText(line.text, 0, yValue + ctx.lineWidth);
}
}
return;
}
}
};
Chart.pluginService.register(horizonalLinePlugin);
... and then I add it to the bar chart options using the following
options: {
...standard option stuff...
"horizontalLine": [{
"y": averageValue,
"style" : colorOfTheLine
}]
}
Which generates a chart that looks like the one below.
..however when you hover on a segment of the chart to display the tooltip, and the tooltip is in the path of the horizontal line, it causes the issue seen below.
Attach your plugin to the afterDatasetDraw hook, instead of afterDraw . This will make the horizontal line to be drawn before the tooltip.
var horizonalLinePlugin = {
afterDatasetDraw: function(chartInstance) {
var yScale = chartInstance.scales["y-axis-0"];
var canvas = chartInstance.chart;
var ctx = canvas.ctx;
var index, line, style, width;
if (chartInstance.options.horizontalLine) {
for (index = 0; index < chartInstance.options.horizontalLine.length; index++) {
line = chartInstance.options.horizontalLine[index];
style = (line.style) ? line.style : "rgba(169,169,169, .6)";
yValue = (line.y) ? yScale.getPixelForValue(line.y) : 0;
ctx.lineWidth = (line.width) ? line.width : 3;
if (yValue) {
ctx.beginPath();
ctx.moveTo(chartInstance.chartArea.left, yValue);
ctx.lineTo(canvas.width, yValue);
ctx.strokeStyle = style;
ctx.stroke();
}
if (line.text) {
ctx.fillStyle = style;
ctx.fillText(line.text, 0, yValue + ctx.lineWidth);
}
}
return;
}
}
};
Chart.pluginService.register(horizonalLinePlugin);
new Chart(canvas, {
type: 'bar',
data: {
labels: ["January", "February"],
datasets: [{
label: "Dataset 1",
data: [80, 50]
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
},
horizontalLine: [{
y: 50,
style: 'red'
}]
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="canvas"></canvas>

Adding a label to a doughnut chart in Chart.js shows all values in each chart

I'm using Chart.js to draw a series of charts on my site and I've written a helper method to draw different charts easily:
drawChart(ctxElement, ctxType, ctxDataLabels, ctxDataSets, midLabel) {
var ctx = ctxElement;
var data = {
labels: ctxDataLabels,
datasets: ctxDataSets
};
Chart.pluginService.register({
beforeDraw: function(chart) {
var width = chart.chart.width,
height = chart.chart.height,
ctx = chart.chart.ctx;
ctx.restore();
var fontSize = (height / 114).toFixed(2);
ctx.font = fontSize + "em sans-serif";
ctx.textBaseline = "middle";
var text = midLabel,
textX = Math.round((width - ctx.measureText(text).width) / 2),
textY = height / 2;
ctx.fillText(text, textX, textY);
ctx.save();
}
});
var chart = new Chart(ctx, {
type: ctxType,
data: data,
options: {
legend: {
display: false
},
responsive: true
}
});
}
The last parameter for the drawChart() method contains the label that should be added in the middle of the chart. The Chart.pluginService.register part is the code that draws the label. The problem is that when I execute the drawChart method multiple times (in my case three times) and supply the label of each chart in the method executions, all three labels are shown on top of each other on each chart. I need to display each label in the corresponding chart. All other parameters are handled correctly, except for the label.
How do I achieve that?
A simple workaround is to add another parameter to your function to differentiate your charts from each other.
I chose to use the id of a chart for this, so that you are sure you won't affect another one.
You first need to edit a little bit your function :
// !!
// Don't forget to change the prototype
// !!
function drawChart(ctxElement, ctxType, ctxDataLabels, ctxDataSets, midLabel, id) {
var ctx = ctxElement;
var data = {
labels: ctxDataLabels,
datasets: ctxDataSets
};
Chart.pluginService.register({
afterDraw: function(chart) {
// Makes sure you work on the wanted chart
if (chart.id != id) return;
// From here, it is the same as what you had
var width = chart.chart.width,
height = chart.chart.height,
ctx = chart.chart.ctx;
// ...
}
});
// ...
}
From now, when you call your function, don't forget about the id :
// ids need to be 0, 1, 2, 3 ...
drawChart(ctxElement, ctxType, ctxDataLabels, ctxDataSets, "Canvas 1", 0);
drawChart(ctxElement, ctxType, ctxDataLabels, ctxDataSets, "Canvas 2", 1);
drawChart(ctxElement, ctxType, ctxDataLabels, ctxDataSets, "Canvas 3", 2);
You can see a fully working example on this fiddle (with 3 charts), and here is a preview :

pie chart use line point to percentage text [duplicate]

I am using Chart.js for drawing pie chart in my php page.I found tooltip as showing each slice values.
But I wish to display those values like below image.
I do not know how to do this with chart.js.
Please help me.
My Javascript code:
function drawPie(canvasId,data,legend){
var ctx = $("#pie-canvas-" + canvasId).get(0).getContext("2d");
var piedata = [];
$.each(data,function(i,val){
piedata.push({value:val.count,color:val.color,label:val.status});
});
var options =
{
tooltipTemplate: "<%= Math.round(circumference / 6.283 * 100) %>%",
}
var pie = new Chart(ctx).Pie(piedata,options);
if(legend)document.getElementById("legend").innerHTML = pie.generateLegend();
}
php code:
printf('<table><tr>');
echo '<td style="text-align: right;"><canvas id="pie-canvas-'
. $canvasId
. '" width="256" height="256" ></canvas></td><td style="text-align: left;width:360px;height:auto" id="legend" class="chart-legend"></td></tr></table>';
echo '<script type="text/javascript">drawPie('
. $canvasId
. ', '
. $data3
.', '
. $legend
. ');</script>';
For Chart.js 2.0 and up, the Chart object data has changed. For those who are using Chart.js 2.0+, below is an example of using HTML5 Canvas fillText() method to display data value inside of the pie slice. The code works for doughnut chart, too, with the only difference being type: 'pie' versus type: 'doughnut' when creating the chart.
Script:
Javascript
var data = {
datasets: [{
data: [
11,
16,
7,
3,
14
],
backgroundColor: [
"#FF6384",
"#4BC0C0",
"#FFCE56",
"#E7E9ED",
"#36A2EB"
],
label: 'My dataset' // for legend
}],
labels: [
"Red",
"Green",
"Yellow",
"Grey",
"Blue"
]
};
var pieOptions = {
events: false,
animation: {
duration: 500,
easing: "easeOutQuart",
onComplete: function () {
var ctx = this.chart.ctx;
ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontFamily, 'normal', Chart.defaults.global.defaultFontFamily);
ctx.textAlign = 'center';
ctx.textBaseline = 'bottom';
this.data.datasets.forEach(function (dataset) {
for (var i = 0; i < dataset.data.length; i++) {
var model = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._model,
total = dataset._meta[Object.keys(dataset._meta)[0]].total,
mid_radius = model.innerRadius + (model.outerRadius - model.innerRadius)/2,
start_angle = model.startAngle,
end_angle = model.endAngle,
mid_angle = start_angle + (end_angle - start_angle)/2;
var x = mid_radius * Math.cos(mid_angle);
var y = mid_radius * Math.sin(mid_angle);
ctx.fillStyle = '#fff';
if (i == 3){ // Darker text color for lighter background
ctx.fillStyle = '#444';
}
var percent = String(Math.round(dataset.data[i]/total*100)) + "%";
//Don't Display If Legend is hide or value is 0
if(dataset.data[i] != 0 && dataset._meta[0].data[i].hidden != true) {
ctx.fillText(dataset.data[i], model.x + x, model.y + y);
// Display percent in another line, line break doesn't work for fillText
ctx.fillText(percent, model.x + x, model.y + y + 15);
}
}
});
}
}
};
var pieChartCanvas = $("#pieChart");
var pieChart = new Chart(pieChartCanvas, {
type: 'pie', // or doughnut
data: data,
options: pieOptions
});
HTML
<canvas id="pieChart" width=200 height=200></canvas>
jsFiddle
I found an excellent Chart.js plugin that does exactly what you want:
https://github.com/emn178/Chart.PieceLabel.js
From what I know I don't believe that Chart.JS has any functionality to help for drawing text on a pie chart. But that doesn't mean you can't do it yourself in native JavaScript. I will give you an example on how to do that, below is the code for drawing text for each segment in the pie chart:
function drawSegmentValues()
{
for(var i=0; i<myPieChart.segments.length; i++)
{
// Default properties for text (size is scaled)
ctx.fillStyle="white";
var textSize = canvas.width/10;
ctx.font= textSize+"px Verdana";
// Get needed variables
var value = myPieChart.segments[i].value;
var startAngle = myPieChart.segments[i].startAngle;
var endAngle = myPieChart.segments[i].endAngle;
var middleAngle = startAngle + ((endAngle - startAngle)/2);
// Compute text location
var posX = (radius/2) * Math.cos(middleAngle) + midX;
var posY = (radius/2) * Math.sin(middleAngle) + midY;
// Text offside to middle of text
var w_offset = ctx.measureText(value).width/2;
var h_offset = textSize/4;
ctx.fillText(value, posX - w_offset, posY + h_offset);
}
}
A Pie Chart has an array of segments stored in PieChart.segments, we can look at the startAngle and endAngle of these segments to determine the angle in between where the text would be middleAngle. Then we would move in that direction by Radius/2 to be in the middle point of the chart in radians.
In the example above some other clean-up operations are done, due to the position of text drawn in fillText() being the top right corner, we need to get some offset values to correct for that. And finally textSize is determined based on the size of the chart itself, the larger the chart the larger the text.
Fiddle Example
With some slight modification you can change the discrete number values for a dataset into the percentile numbers in a graph. To do this get the total value of the items in your dataset, call this totalValue. Then on each segment you can find the percent by doing:
Math.round(myPieChart.segments[i].value/totalValue*100)+'%';
The section here myPieChart.segments[i].value/totalValue is what calculates the percent that the segment takes up in the chart. For example if the current segment had a value of 50 and the totalValue was 200. Then the percent that the segment took up would be: 50/200 => 0.25. The rest is to make this look nice. 0.25*100 => 25, then we add a % at the end. For whole number percent tiles I rounded to the nearest integer, although can can lead to problems with accuracy. If we need more accuracy you can use .toFixed(n) to save decimal places. For example we could do this to save a single decimal place when needed:
var value = myPieChart.segments[i].value/totalValue*100;
if(Math.round(value) !== value)
value = (myPieChart.segments[i].value/totalValue*100).toFixed(1);
value = value + '%';
Fiddle Example of percentile with decimals
Fiddle Example of percentile with integers
You can make use of PieceLabel plugin for Chart.js.
{ pieceLabel: { mode: 'percentage', precision: 2 } }
Demo |
Documentation
The plugin appears to have a new location (and name): Demo Docs.
#Hung Tran's answer works perfect. As an improvement, I would suggest not showing values that are 0. Say you have 5 elements and 2 of them are 0 and rest of them have values, the solution above will show 0 and 0%. It is better to filter that out with a not equal to 0 check!
var val = dataset.data[i];
var percent = String(Math.round(val/total*100)) + "%";
if(val != 0) {
ctx.fillText(dataset.data[i], model.x + x, model.y + y);
// Display percent in another line, line break doesn't work for fillText
ctx.fillText(percent, model.x + x, model.y + y + 15);
}
Updated code below:
var data = {
datasets: [{
data: [
11,
16,
7,
3,
14
],
backgroundColor: [
"#FF6384",
"#4BC0C0",
"#FFCE56",
"#E7E9ED",
"#36A2EB"
],
label: 'My dataset' // for legend
}],
labels: [
"Red",
"Green",
"Yellow",
"Grey",
"Blue"
]
};
var pieOptions = {
events: false,
animation: {
duration: 500,
easing: "easeOutQuart",
onComplete: function () {
var ctx = this.chart.ctx;
ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontFamily, 'normal', Chart.defaults.global.defaultFontFamily);
ctx.textAlign = 'center';
ctx.textBaseline = 'bottom';
this.data.datasets.forEach(function (dataset) {
for (var i = 0; i < dataset.data.length; i++) {
var model = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._model,
total = dataset._meta[Object.keys(dataset._meta)[0]].total,
mid_radius = model.innerRadius + (model.outerRadius - model.innerRadius)/2,
start_angle = model.startAngle,
end_angle = model.endAngle,
mid_angle = start_angle + (end_angle - start_angle)/2;
var x = mid_radius * Math.cos(mid_angle);
var y = mid_radius * Math.sin(mid_angle);
ctx.fillStyle = '#fff';
if (i == 3){ // Darker text color for lighter background
ctx.fillStyle = '#444';
}
var val = dataset.data[i];
var percent = String(Math.round(val/total*100)) + "%";
if(val != 0) {
ctx.fillText(dataset.data[i], model.x + x, model.y + y);
// Display percent in another line, line break doesn't work for fillText
ctx.fillText(percent, model.x + x, model.y + y + 15);
}
}
});
}
}
};
var pieChartCanvas = $("#pieChart");
var pieChart = new Chart(pieChartCanvas, {
type: 'pie', // or doughnut
data: data,
options: pieOptions
});
For Chart.js 3
I've modified "Hung Tran"'s Code.
animation: {
onProgress: function() {
// console.error('this', this);
const ctx = this.ctx;
// ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontFamily, 'normal', Chart.defaults.global.defaultFontFamily);
ctx.textAlign = 'center';
ctx.textBaseline = 'bottom';
let dataSum = 0;
if(this._sortedMetasets.length > 0 && this._sortedMetasets[0].data.length > 0) {
const dataset = this._sortedMetasets[0].data[0].$context.dataset;
dataSum = dataset.data.reduce((p, c) => p + c, 0);
}
if(dataSum <= 0) return;
this._sortedMetasets.forEach(meta => {
meta.data.forEach(metaData => {
const dataset = metaData.$context.dataset;
const datasetIndex = metaData.$context.dataIndex;
const value = dataset.data[datasetIndex];
const percent = (Math.round(value / dataSum * 1000) / 10) + '%';
const mid_radius = metaData.innerRadius + (metaData.outerRadius - metaData.innerRadius) * 0.7;
const start_angle = metaData.startAngle;
const end_angle = metaData.endAngle;
if(start_angle === end_angle) return; // hidden
const mid_angle = start_angle + (end_angle - start_angle) / 2;
const x = mid_radius * Math.cos(mid_angle);
const y = mid_radius * Math.sin(mid_angle);
ctx.fillStyle = '#fff';
ctx.fillText(percent, metaData.x + x, metaData.y + y + 15);
});
});
}
}
Give the option for pie chart
onAnimationProgress: drawSegmentValues
like:
var pOptions = {
onAnimationProgress: drawSegmentValues
};
var pieChart = new Chart(pieChartCanvas, {
type: 'pie', // or doughnut
data: data,
options: pOptions
});
Easiest way to do this with Chartjs. Just add below line in options:
pieceLabel: {
fontColor: '#000'
}
Best of luck

Scrollable x axis with chart.js 2.1.4

I have a line graph with lot of points to plot
I want x axis to be scrollable
I have already looked few solutions but they are providing solution with old versions of chart js.
Is there any option to get scrollable x axis in chart.js version 2?
And
How can i get width of content in y axis in chart.js version 2?
if there is no direct option to get scrollable x axis, I can copy content in Y-axis region and draw image in other canvas.
My answer on a related question will help you. In my example I have made the Y axis scrollable, but this could easily be applied to the X axis too.
https://stackoverflow.com/a/51282003/10060003
JS fiddle - https://jsfiddle.net/EmmaLouise/eb1aqpx8/3/
I am using the animation onComplete and onProgress options to redraw the axis that I want to scroll with the chart. (See https://www.chartjs.org/docs/latest/configuration/animations.html).
$(function () {
var rectangleSet = false;
var canvasTest = $('#chart-Test');
var chartTest = new Chart(canvasTest, {
type: 'bar',
data: chartData,
maintainAspectRatio: false,
responsive: true,
options: {
tooltips: {
titleFontSize: 0,
titleMarginBottom: 0,
bodyFontSize: 12
},
legend: {
display: false
},
scales: {
xAxes: [{
ticks: {
fontSize: 12,
display: false
}
}],
yAxes: [{
ticks: {
fontSize: 12,
beginAtZero: true
}
}]
},
animation: {
onComplete: function () {
if (!rectangleSet) {
var scale = window.devicePixelRatio;
var sourceCanvas = chartTest.chart.canvas;
var copyWidth = chartTest.scales['y-axis-0'].width - 10;
var copyHeight = chartTest.scales['y-axis-0'].height + chartTest.scales['y-axis-0'].top + 10;
var targetCtx = document.getElementById("axis-Test").getContext("2d");
targetCtx.scale(scale, scale);
targetCtx.canvas.width = copyWidth * scale;
targetCtx.canvas.height = copyHeight * scale;
targetCtx.canvas.style.width = `${copyWidth}px`;
targetCtx.canvas.style.height = `${copyHeight}px`;
targetCtx.drawImage(sourceCanvas, 0, 0, copyWidth * scale, copyHeight * scale, 0, 0, copyWidth * scale, copyHeight * scale);
var sourceCtx = sourceCanvas.getContext('2d');
// Normalize coordinate system to use css pixels.
sourceCtx.clearRect(0, 0, copyWidth * scale, copyHeight * scale);
rectangleSet = true;
}
},
onProgress: function () {
if (rectangleSet === true) {
var copyWidth = chartTest.scales['y-axis-0'].width;
var copyHeight = chartTest.scales['y-axis-0'].height + chartTest.scales['y-axis-0'].top + 10;
var sourceCtx = chartTest.chart.canvas.getContext('2d');
sourceCtx.clearRect(0, 0, copyWidth, copyHeight);
}
}
}
}
});

Categories