How to display grouped bar chart using chart.js? - angular-material

I am currently building a grouped bar chart, with two different datasets using chart.js. The code in the component.js file is as follows:
createChart(){
var lbls = ['Selling', 'Cost', 'Gross'];
var curYearData = [2345, 1234, 1111];
var preYearData = [3456, 2345, 1111];
var ctx = document.getElementById(‘barChart') as HTMLCanvasElement;
var barChart = new Chart(ctx, {
type: 'bar',
data: {
labels: lbls,
datasets: [
{
label: ‘2020',
data: curYearData,
backgroundColor: 'blue',
},
{
label: ‘2019',
data: preYearData,
backgroundColor: 'red',
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
}
However, I see no data displayed and instead I get an empty screen. How to create a grouped bar chart in chart.js?

There are two problems in your code.
First you don't correctly retrieve the 2D-Context.
var ctx = document.getElementById('barChart').getContext('2d');
Further you have some strange apostrophes that need to be changed.
Please have a look at your amended code below.
var lbls = ['Selling', 'Cost', 'Gross'];
var curYearData = [2345, 1234, 1111];
var preYearData = [3456, 2345, 1111];
var ctx = document.getElementById('barChart').getContext('2d');
var barChart = new Chart(ctx, {
type: 'bar',
data: {
labels: lbls,
datasets: [{
label: '2020',
data: curYearData,
backgroundColor: 'blue',
},
{
label: '2019',
data: preYearData,
backgroundColor: 'red',
}
]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="barChart"></canvas>

Related

How to format tool tip as currency in piechart chartJS?

I am using chartJS in my rails app and my chart code is added below. When hovering over sections I need to display as "Label name: $ 636"...Now when hovering it displays as "Label name: 636". The current chart with tooltip is
var ctx = document.getElementById('dollar-issue-area').getContext('2d');
var that = this;
this.chart = new Chart(ctx, {
type: 'pie',
data: {
labels: <%= raw dollar_per_type.collect { |k, v| k } %>,
datasets: [{
label: 'Number of tickets',
data: <%= raw dollar_per_type.collect { |k, v| v } %>,
backgroundColor: palette('tol-dv', <%= raw dollar_per_type.collect { |k, v| k }.length %>).map(function(hex) {return '#' + hex;})
}]
},
options: {
title:{
display: true,
text: 'Dollar per Sub Issue Type from <%= start_date %> to <%= end_date %>'
},
legend: {
display: true,
labels: {
display: false,
fontSize: 10
}
}
}
});
you can use a tooltips callback function.
here, the label callback is used to customize the tooltip content...
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
return data['labels'][tooltipItem['index']] + ': $' + data['datasets'][0]['data'][tooltipItem['index']];
}
}
}
see following working snippet...
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'pie',
data: {
labels: ['confirmed', 'pending'],
datasets: [{
data: [67, 33],
backgroundColor: [
'rgba(41, 121, 255, 1)',
'rgba(38, 198, 218, 1)'
],
}]
},
options: {
title: {
display: true,
text: 'Dollar per Sub Issue Type'
},
legend: {
display: true,
labels: {
display: false,
fontSize: 10
}
},
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
return data['labels'][tooltipItem['index']] + ': $' + data['datasets'][0]['data'][tooltipItem['index']];
}
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.bundle.min.js"></script>
<canvas id="myChart"></canvas>

What is the highchart pie data structure

I have create a HighCharts Pie as follows :
This a parts of my source:
series: [{
name: 'Temps d\'arrêt',
type: 'pie',
data: getTempsDArretSeries(data2),
center: [35, 0],
size: 100,
showInLegend: false,
dataLabels: {
enabled: false
}
,tooltip: {
valueSuffix: ' min '+'<br><b>{point.percentage:.1f}%</b>',
}
,title: {
text: 'Temps d\'arrêt'
},
}]
My function getTempsDArretSeries(data2) is :
function getTempsDArretSeries(data){
var array = new Array();
var duree = 0;
var memProduit = 0;
$(data).each(function(){
if(memProduit!=0){
if(memProduit != parseInt(this.efcode)){
array.push(duree);
memProduit = parseInt(this.efcode);
duree = parseInt(this.efdur);
}else{
duree += parseInt(this.efdur);
}
}else{
duree += parseInt(this.efdur);
memProduit = parseInt(this.efcode);
}
})
array.push(duree);
return array;
}
I have the result as follows on my chart :
chart
It is possible to put something like :
name: memProduit,
y: duree,
sliced: true,
selected: true
for all lines.
Thanks,
Regards,

Highcharts more than one series

I have a simple json document :
[ {
"x" : "a",
"y" : 2
}, {
"x" : "b",
"y" : 8
}, {
"x" : "c",
"y" : 4
}, {
"x" : "d",
"y" : 15
} ]
I want to visualize it using Highcharts having 4 series. I could success, however, the data appeared only as one series (see the next Figure).
Here is part of the code:
var options = {
.
.
.
series: [{ }]
};
.
.
.
var data = JSON.parse(json);
var seriesData = [];
for (var i = 0; i < data.length; i++) {
seriesData.push([data[i].x, data[i].y]);
options.xAxis.categories.push( data[i].x );
}
options.series[0].data = seriesData;
var chart = new Highcharts.Chart(options);
also updating the series
chart.series[0].update({
type: type,
});
works fine.
using
options.series.push({name: data[i].x, data: [data[i].x, data[i].y]});
creates 4 series but not appropriately visualized and also updating the series
chart.series[0].update({
type: type,
});
doesn't work, therefore, I want to focus in the first mentioned method.
any hints?
EDit: code which partially works for me:
var options = {
chart: {
renderTo: 'container',
type: 'column' //default
},
title: {
text: ''
},
yAxis: {
title: {
enabled: true,
text: 'Count',
style: {
fontWeight: 'normal'
}
}
},
xAxis: {
title: {
enabled: true,
text: '',
style: {
fontWeight: 'normal'
}
},
categories: [],
crosshair: true
} ,
plotOptions: {
pie: {
innerSize: 125,
depth: 80
},
column: {
pointPadding: 0.2,
borderWidth: 0,
grouping: false
}
},
series: [{ }]
};
// Set type
$.each(['column', 'pie'], function (i, type) {
$('#' + type).click(function () {
chart.series[0].update({
type: type
});
});
var data = get the data fom json file**
var seriesData = [];
for (var i = 0; i < data.length; i++) {
seriesData.push([data[i].x, data[i].y]);
options.xAxis.categories.push( data[i].x );
}
options.series[0].data = seriesData;
var chart = new Highcharts.Chart(options);
});
});
You have to decide whether you want to have 4 different series and update all 4 series at once or you want to have one series an then build e.g. legend on your own.
If you want to have 4 series, set grouping to false, set xAxis categories and each point should be mapped to one series with one point - the point.x should have the index of the series.
const series = data.map((point, x) => ({ name: point.x, data: [{ x, y: point.y }]}))
const chart = Highcharts.chart('container', {
chart: {
type: 'column'
},
plotOptions: {
column: {
grouping: false
}
},
xAxis: {
categories: data.map(point => point.x)
},
series: series
});
Then you can update your all 4 series:
chart.series.forEach(series => series.update({
type: series.type === 'column' ? 'scatter' : 'column'
}, false))
chart.redraw()
example: http://jsfiddle.net/pdjqrj5y/

How to change highmap bubble color

I am trying to color the bubbles based on the name of the cities. Something like if this.point.capital == Montgomery & this.point.capital == Juneau; color = "red". But I cannot add this if function to the color attribute. Can you help me out?
Thanks!!!!
series: [{
name: 'Basemap',
mapData: map,
borderColor: '#606060',
nullColor: 'rgba(200, 200, 200, 0.2)',
showInLegend: false
}, {
name: 'Separators',
type: 'mapline',
data: H.geojson(map, 'mapline'),
color: '#101010',
enableMouseTracking: false
}, {
type: 'mapbubble',
dataLabels: {
enabled: true,
format: '{point.capital}'
},
name: 'Cities',
data: data,
maxSize: '12%',
color: H.getOptions().colors[0]
}]
http://jsfiddle.net/oufwhmz0/
Do this for each bubble individually (not the series as a whole) in the data array prior to initiating the chart. For example extending your code (JSFiddle):
function determineColor(entry) {
if(entry.capital == "Montgomery")
return "#FF00FF";
else if(entry.capital == "Salt Lake City")
return "#00FF00";
return null;
}
// Add series with state capital bubbles
$.getJSON('http://www.highcharts.com/samples/data/jsonp.php?filename=us-capitals.json&callback=?', function (json) {
var data = [];
$.each(json, function (ix, entry) {
entry.z = entry.population;
entry.color = determineColor(entry); // Added
data.push(entry);
});
// ... rest as usual
});
This just sets the color for each entry (which will be a bubble), as defined by the determineColor function.

Recveived error from phantomjs:ERROR: While rendering, there's is a timeout reached

I have some error while exporting the chart. I am using the exporting.js from Highcharts
Export PNG, JPEG, PDF received the below error.
Export SVG ok. But can't see the image.
Oops..,
Something went wrong while converting. recveived error from phantomjs:ERROR: While rendering, there's is a timeout reached
function renderChartPie(divId, chartType, chartTitle, chartCriteria, chartData, categories) {
var data = jQuery.parseJSON(chartData);
var cat = jQuery.parseJSON(categories);
var options = createOptionPie(divId, chartType, chartTitle, chartCriteria, cat);
options.series = [{
data : data
}];
var chart = new Highcharts.Chart(options);
}
function createOptionPie(divId, chartType, chartTitle, chartCriteria, categories) {
var options = {
colors : [ '#2f7ed8', '#0d233a', '#8bbc21', '#910000', '#1aadce',
'#492970', '#f28f43', '#77a1e5', '#c42525', '#a6c96a',
'#4572A7', '#AA4643', '#89A54E', '#80699B', '#3D96AE',
'#DB843D', '#92A8CD', '#A47D7C', '#B5CA92' ],
chart : {
renderTo : divId,
type : chartType,
events: {
load: function() {
var text = this.renderer.text('<br/>' + chartCriteria, 0, 445).css({
fontSize : 9
}).add();
var image = this.renderer.image('../../theme/50x71.png', 630, 409, 70, 51)
.add();
}
}
},
credits : {
enabled : false
},
legend : {
align: 'right',
verticalAlign: 'middle',
layout : 'vertical'
},
title : {
text : chartTitle
},
tooltip: {
formatter: function() {
return this.point.name +': '+ Highcharts.numberFormat(this.y,0) ;
}
},
xAxis : {
categories : categories
},
yAxis: {
},
plotOptions: {
pie: {
allowPointSelect : true,
showInLegend : true
}
},
series : []
};
return options;
}
The problem with timeout, because calling function (export) is limited. If problem will still appear, please prepare your own exporting server. Instructions are available here: http://www.highcharts.com/component/content/article/2-news/56-improved-image-export-with-phantomjs

Resources