Chart bar with codeigniter 3 - javascript

I want to create a chart with the chart bar and list all the new records that I added in my database and get the month it was added.
The problem is my application is in php and I saw that chart.js is in javascript.
This is the html of my chart that is in index.php
<div class="row clearfix">
<!-- Bar Chart -->
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="card">
<div class="header">
<h2>GuiaCorretor - Analitycs</h2>
</div>
<div class="body">
<canvas id="bar_chart" height="50"></canvas>
</div>
</div>
</div>
<!-- #END# Bar Chart -->
</div>
And this is the code that is in my javascript, but here there is no link to my database, how could I sync my javascript and get this information?
$(function () {
//new Chart(document.getElementById("line_chart").getContext("2d"), getChartJs('line'));
new Chart(document.getElementById("bar_chart").getContext("2d"), getChartJs('bar'));
//new Chart(document.getElementById("radar_chart").getContext("2d"), getChartJs('radar'));
//new Chart(document.getElementById("pie_chart").getContext("2d"), getChartJs('pie'));
});
function getChartJs(type) {
var config = null;
if (type === 'bar') {
config = {
type: 'bar',
data: {
labels: ["JANEIRO", "FEVEREIRO", "MARÇO", "ABRIL", "MAIO", "JUNHO", "JULHO", "AGOSTO", "SETEMBRO", "OUTUBRO", "NOVEMBRO", "DEZEMBRO"],
datasets: [{
label: "Imóveis cadastrados",
data: [65, 59, 80, 81, 56, 55, 40],
backgroundColor: 'rgba(0, 188, 212, 0.8)'
}, {
label: "Imóveis cadastrados",
data: [28, 48, 40, 19, 86, 27, 90],
backgroundColor: 'rgba(233, 30, 99, 0.8)'
}]
},
options: {
responsive: true,
legend: false
}
}
}
return config;
}

One way is to use your controller to create the data in an array format, and pass that data into your view as a json string.
In php create the data array that .js needs:
$chartData = [
'labels' => ['Janeiro', 'Fevereiro', ...],
'datasets' => [
[
'label' => "Imóveis cadastrados",
'data' => [65, 59, 80, 81, 56, 55, 40],
'backgroundColor' => 'rgba(0, 188, 212, 0.8)'
],
[...]
]
];
Then json_encode that data as a data attribute of your canvas (the syntax here will vary depending on what method you use to pass dynamic data into your view, I will use raw PHP here for demonstration):
<canvas id="bar_chart" height="50" data-chart-data="<?php json_encode($chartData); ?>"></canvas>
And then lastly use the json contained in that data attribute to power your chart:
config = {
type: 'bar',
data: document.getElementById("bar_chart").data('chart-data'),
options: {
responsive: true,
legend: false
}
}

Related

How to hide the legend display for a specific chart?

What I'm trying now is if I have 1 chart and then, when I click on a button with the "onchange" function, it'll display several chart. But when I'm clicking back, I have the chart I want but there is still the "legend" of the 2nd chart in the top of the 1st chart.
Is there a way to remove it ? I've found options: { legend: { display: false } but it remove the legend for all the chart.
Here is my code
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"
integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ=="
crossorigin="anonymous"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
<script src="https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.8.0"></script>
</head>
<body>
<div class="row mt-3">
<div class="col-md-12">
<div style="width:75%; margin: 0 auto;">
<canvas id="myChart"></canvas>
</div>
<div class="form-check form-switch">
<input class="form-check-input" type="checkbox" id="checkBox" onchange="toggleCategories(event)">
<label class="form-check-label" for="checkBox">Catégories</label>
</div>
</div>
</div>
<script>
var test1 = [0, 10, 5, 2, 20, 30, 45, 60, 43, 22, 11, 23];
var test2 = [90, 80, 75, 62, 50, 40, 35, 11, 2, 24, 28, 34];
var test3 = [90, 10, 90, 10, 50, 40, 23, 62, 13, 32, 11, 13];
var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
// The type of chart we want to create
type: 'line',
// The data for our dataset
data: {
labels: ['January', 'February', 'test3', 'test4', 'test5', 'test6', 'test7', 'test9', 'test10', 'test11', 'test12'],
datasets: [{
label: 'My test1',
fill : false,
borderColor: 'rgb(255, 99, 132)',
data: test1,
}, {fill : false
}]
},
// Configuration options go here
options: {}
});
function toggleCategories(e){
if (e.target.checked) {
chart.data.datasets[0].label = 'My test2';
chart.data.datasets[0].data = test2;
chart.data.datasets[0].borderColor = 'rgb(255, 99, 132)';
chart.data.datasets[1].label = 'My test3';
chart.data.datasets[1].data = test3;
chart.data.datasets[1].borderColor = 'rgb(255, 99, 132)';
} else {
chart.data.datasets[0].label = 'My test1';
chart.data.datasets[0].data = test1;
chart.data.datasets[0].borderColor = 'rgb(255, 99, 132)';
chart.data.datasets[1].label = '';
chart.data.datasets[1].data = '';
chart.data.datasets[1].borderColor = '';
}
chart.update();
}
</script>
</body>
</html>
Cordially
Chart.js highly depends on its data. Therefore, the easiest way is just dynamically populating the necessary data to your chart whenever you need it. This should add and remove the legend as expected. However, don't forget updating your chart on data change.
Let's add some code to get an idea about it, since basically you're actually doing it - but just a little bit wrong.
The data of your chart is stored in dataset. As we can see you have 2 entries whereas the 2nd one is just an object containing a boolean property (fill). Therefore, it's displaying undefined in your legend at the very beginning.
datasets: [{
label: 'My test1',
fill: false,
borderColor: 'rgb(255, 99, 132)',
data: test1,
}, {
fill: false
}]
However, when toggling the the checkbox it looks fine, since you're overwriting everything within your toggleCategories as seen below.
function toggleCategories(e) {
if (e.target.checked) {
chart.data.datasets[0].label = 'My test2';
chart.data.datasets[0].data = test2;
chart.data.datasets[0].borderColor = 'rgb(255, 99, 132)';
chart.data.datasets[1].label = 'My test3';
chart.data.datasets[1].data = test3;
chart.data.datasets[1].borderColor = 'rgb(255, 99, 132)';
} else {
...
}
chart.update();
}
But taking a closer look to else shows what's going on here.
// Those 3 lines just reset on index 1, it doesn't get deleted
chart.data.datasets[1].label = '';
chart.data.datasets[1].data = '';
chart.data.datasets[1].borderColor = '';
So in order to get rid of the 2nd legend when you only want 1, you simply have to remove the object of dataset[1] and re-add it whenever you need it.
You might want to look into this fiddle for a fully working example:
It could be a solution?
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"
integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ=="
crossorigin="anonymous"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
<script src="https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.8.0"></script>
</head>
<body>
<div class="row mt-3">
<div class="col-md-12">
<div>
<h5 id="legend" style="text-align: center;">My test 1</h5>
</div>
<div style="width:75%; margin: 0 auto;">
<canvas id="myChart"></canvas>
</div>
<div class="form-check form-switch">
<input class="form-check-input" type="checkbox" id="checkBox" onchange="toggleCategories(event)">
<label class="form-check-label" for="checkBox">Catégories</label>
</div>
</div>
</div>
<script>
var test1 = [0, 10, 5, 2, 20, 30, 45, 60, 43, 22, 11, 23];
var test2 = [90, 80, 75, 62, 50, 40, 35, 11, 2, 24, 28, 34];
var test3 = [90, 10, 90, 10, 50, 40, 23, 62, 13, 32, 11, 13];
var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
// The type of chart we want to create
type: 'line',
// The data for our dataset
data: {
labels: ['January', 'February', 'test3', 'test4', 'test5', 'test6', 'test7', 'test9', 'test10', 'test11', 'test12'],
datasets: [{
label: 'My test1',
fill : false,
borderColor: 'rgb(255, 99, 132)',
data: test1,
}, {fill : false
}]
},
// Configuration options go here
options: {legend:{display: false}}
});
function toggleCategories(e){
if (e.target.checked) {
changeLegendOnCl();
chart.data.datasets[0].label = 'My test2';
chart.data.datasets[0].data = test2;
chart.data.datasets[0].borderColor = 'rgb(255, 99, 132)';
chart.data.datasets[1].label = 'My test3';
chart.data.datasets[1].data = test3;
chart.data.datasets[1].borderColor = 'rgb(255, 99, 132)';
} else {
document.getElementById("legend").innerHTML = "My test 1";
chart.data.datasets[0].label = 'My test1';
chart.data.datasets[0].data = test1;
chart.data.datasets[0].borderColor = 'rgb(255, 99, 132)';
chart.data.datasets[1].label = 'My test1';
chart.data.datasets[1].data = test1;
chart.data.datasets[1].borderColor = 'rgb(255, 99, 132)';
}
chart.update();
}
function changeLegendOnCl(){
document.getElementById("legend").innerHTML = "My test 2"+" "+"My test 3";
}
</script>
</body>
</html>

Hide textinfo of piechartjs which are extended outside the piechart - plotly js

I am using Plotly to show a pie chart. My code looks like:
let dataKeyValue = {
'ADA': 660,
'Affordable': 49,
'Balcony': 2546,
'Bathroom': 157,
'Ceiling': 337,
'Closet/Storage': 23,
'Corner': 577,
'DOM': 321,
'Finishes': 1455,
'Floor Level': 6205,
'Floor Plan or Layout': 569,
'Flooring': 242,
'Kitchen': 4543,
'Location': 3462,
'Loft': 12,
'Renovation': 1438,
'Rent': 658,
'Square Feet': 2114,
'Unclear': 1692,
'Unit Features': 2544,
'View/Exposure': 4703,
'Washer/Dryer': 2037,
'Windows': 340,
'private entry': 8
};
let dollarSign = "$";
let pieData = [{
values: Object.values(dataKeyValue),
labels: Object.keys(dataKeyValue),
type: 'pie',
textinfo: "label",
hoverinfo: "label+percent",
// texttemplate: "%{label}<br>"+dollarSign+"%{value}<br>%{percent}",
hovertemplate: "%{label}<br>"+dollarSign+"%{value}<br>%{percent}"
}];
var layout = {
margin: {"t": 0, "b": 0, "l": 0, "r": 0},
showlegend: false,
};
Plotly.newPlot('myDiv', pieData, layout);
<head>
<!-- Load plotly.js into the DOM -->
<script src='https://cdn.plot.ly/plotly-latest.min.js'></script>
</head>
<body>
<div id='myDiv'><!-- Plotly chart will be drawn inside this DIV --></div>
</body>
The pie chart is working fine, but the labels of each slice are showing outside the pie chart. I am trying to get rid of those labels which are not inside the pie chart.
To remove the labels, I have found the options as textinfo: "none", but this is removing the labels completely, which means it is removing labels inside the pie chart as well. However, I want to hide only those which are outside the pie chart.
I want to hide that section shown on top right corner. Here is a jsfiddle.
One solution is to set the outside text color to transparent:
let pieData = [{
//...
outsidetextfont: { color: 'transparent' },
}]
Plotly.newPlot('myDiv', pieData, layout)
let dataKeyValue = {
'ADA': 660,
'Affordable': 49,
'Balcony': 2546,
'Bathroom': 157,
'Ceiling': 337,
'Closet/Storage': 23,
'Corner': 577,
'DOM': 321,
'Finishes': 1455,
'Floor Level': 6205,
'Floor Plan or Layout': 569,
'Flooring': 242,
'Kitchen': 4543,
'Location': 3462,
'Loft': 12,
'Renovation': 1438,
'Rent': 658,
'Square Feet': 2114,
'Unclear': 1692,
'Unit Features': 2544,
'View/Exposure': 4703,
'Washer/Dryer': 2037,
'Windows': 340,
'private entry': 8
};
let dollarSign = "$";
let pieData = [{
values: Object.values(dataKeyValue),
labels: Object.keys(dataKeyValue),
type: 'pie',
textinfo: "label",
outsidetextfont: { color: 'transparent' }, // 👈
hoverinfo: "label+percent",
// texttemplate: "%{label}<br>"+dollarSign+"%{value}<br>%{percent}",
hovertemplate: "%{label}<br>"+dollarSign+"%{value}<br>%{percent}"
}];
var layout = {
margin: {"t": 0, "b": 0, "l": 0, "r": 0},
showlegend: false,
};
Plotly.newPlot('myDiv', pieData, layout);
<head>
<!-- Load plotly.js into the DOM -->
<script src='https://cdn.plot.ly/plotly-latest.min.js'></script>
</head>
<body>
<div id='myDiv'><!-- Plotly chart will be drawn inside this DIV --></div>
</body>

How do i make a new chart by pressing a button (chart.js)?

I was wondering if it's possible to go from a bar to a pie-chart by pressing a button?
<script>
var ctx = document.getElementById("myCanvas");
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["2012", "2013", "2014", "2015", "2016", "2017"],
datasets: [{
label: 'Miljoner ton',
data: [56.38, 59.3, 61.81, 58.83, 52.32, 66.86],
backgroundColor: 'rgb(124,181,236)'
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
function adddata() {
myChart.data.datasets[0].data[7] = 14;
myChart.data.labels[7] = "Newly added";
myChart.update();
}
</script>
Follow the perfect link https://codepen.io/mateegojra/pen/GXVOap
var canvas = document.getElementById("barChart");
var ctx = canvas.getContext('2d');
// We are only changing the chart type, so let's make that a global variable along with the chart object:
var chartType = 'bar';
var myBarChart;
// Global Options:
Chart.defaults.global.defaultFontColor = 'grey';
Chart.defaults.global.defaultFontSize = 16;
var data = {
labels: ["2005", "2006", "2007", "2008", "2009", "2010", "2011", "2012", "2013", "2014", "2015", "2016"],
datasets: [{
label: "UFO Sightings",
fill: true,
lineTension: 0.1,
backgroundColor: "rgba(0,255,0,0.4)",
borderColor: "green", // The main line color
borderCapStyle: 'square',
pointBorderColor: "white",
pointBackgroundColor: "green",
pointBorderWidth: 1,
pointHoverRadius: 8,
pointHoverBackgroundColor: "yellow",
pointHoverBorderColor: "green",
pointHoverBorderWidth: 2,
pointRadius: 4,
pointHitRadius: 10,
data: [10, 13, 17, 12, 30, 47, 60, 120, 230, 300, 310, 400],
spanGaps: true,
}]
};
// Notice the scaleLabel at the same level as Ticks
var options = {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
},
title: {
fontSize: 18,
display: true,
text: 'I want to believe !',
position: 'bottom'
}
};
// We add an init function down here after the chart options are declared.
init();
function init() {
// Chart declaration:
myBarChart = new Chart(ctx, {
type: chartType,
data: data,
options: options
});
}
function toggleChart() {
//destroy chart:
myBarChart.destroy();
//change chart type:
this.chartType = (this.chartType == 'bar') ? 'line' : 'bar';
//restart chart:
init();
}
body{
background-color: black;
}
.as-console-wrapper{display: none !important }
#barChart{
background-color:rgba(255,255,255,0.1);
border-radius: 6px;
/* Check out the fancy shadow on this one */
}
.btn{
color:black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.min.js"></script>
<!--
THe post that goes with this pen:
https://codepen.io/k3no/post/learning-by-example-getting-started-with-chart-js
-->
<div class="container">
<br />
<div class="row">
<div class="col-md-1"></div>
<div class="col-md-10">
<!-- Chart.js Canvas Tag -->
<canvas id="barChart"></canvas>
</div>
<div class="col-md-1"></div>
</div>
<br />
<div class="row">
<div class="col-md-1"></div>
<div class="col-md-10"><button type="button" class="btn btn-success btn-md" onclick="toggleChart();">Toggle Chart </button></div>
<div class="col-md-1"></div>
</div>
</div>
Put the following code in your onclick function:
myChart.type = "pie";
myChart.update();

Adapting a JavaScript code to be dynamic

I am kind of new in Jquery,and still learning. I am using Chart.Js in order to render data and AJAX calls.
I created a script that update a Radar Chart using a dropdown Button. The goal in mind is:
Each user is part of a team and has some data that I render in a chart. So I there is some fixed data on the chart using a fixed_array and then the user can compare the current member with other member in the team using the drop down button
I managed to do it with static data with that code but I do not know how to make it dynamic.
I imported the whole team data in the form {user_id : [data_array]} for example :
{6: [81, 68, 71, 71, 67, -72], 7: [79, 77, 86, 86, 59, -71], 8: [67, 71, 68, 68, 85, -66]}
and the current_user id with current_user = data.current_user that return the integer of the ID in this situation 6.
I made a try in a separate file in order to test the chart which look like the following:
<script type="text/javascript">
$(document).ready(function () {
// Different arrays for the different data
var array = [];
array["raphael"] = [90, 20, 80, 50, 34];
array["fraxool"] = [89, 12, 68, 89, 90];
array["johnny"] = [78, 89, 1, 90, 80];
// Default value
var fixed_array = [20, 12, 78, 50, 90];
// Chart config
var color = Chart.helpers.color;
var config = {
type: 'radar',
data: {
labels: [["label1"], "label2", "label3", "label4", "label5"],
datasets: [{
label: "Bugsy Bug 1",
backgroundColor: color(window.chartColors.red).alpha(0.2).rgbString(),
borderColor: window.chartColors.red,
pointBackgroundColor: window.chartColors.red,
data: []
}, {
label: "Bugsy Bug 2",
backgroundColor: color(window.chartColors.blue).alpha(0.2).rgbString(),
borderColor: window.chartColors.blue,
pointBackgroundColor: window.chartColors.blue,
data: fixed_array
}]
},
options: {
legend: {
position: 'top',
display: false
},
title: {
display: false,
text: 'Fiverr Chart'
},
scale: {
ticks: {
beginAtZero: true
},
pointLabels: {
fontSize: 10,
lineHeight: 2
}
}
}
};
var mainChart = new Chart(document.getElementById("canvas"), config);
// Event for the select
$(".pick-chart").change(function (e) {
e.preventDefault();
var val = $(this).val();
if (val != 0) {
config.data.datasets[0].data = array[val];
} else {
config.data.datasets[0].data = [];
}
mainChart.update();
});
});
</script>
But my actual application is getting its data using AJAX:
$.ajax({
method: "GET",
url: endpoint,
success: function(data){
console.log(data)
//Labels comming from wevsite.views//
info_array = data.info_array
current_user = data.current_user
</script>
right now the output of info_array is {6: [81, 68, 71, 71, 67, -72], 7: [79, 77, 86, 86, 59, -71], 8: [67, 71, 68, 68, 85, -66]}
so {user_id: [data]}
and current_user output : 6
I would like to adapt it to use dynamic data that would adapt to any size of team
Could someone help me to figure it out ?
edited code V2:
<div class="col graph-info">
<div class="card">
<h5 class="card-header text-center bg-dark text-white">Information processing</h5>
<div class="card-body">
<div class="dropdown-container">
<form>
<select id="pick-chart" class="form-control pick-chart">
<option value="0">Compare with</option>
{% for i in team_list_pop %}
<option value="{{i.id}}">{{i.first_name}} {{i.last_name}}</option>
{% endfor %}
</select>
</form>
</div>
<canvas id="info_process"></canvas>
</div>
</div>
<script>
var endpoint = 'api/chart/data'
$.ajax({
method: "GET",
url: endpoint,
success: function(data){
console.log(data)
//Labels comming from wevsite.views//
complete_label = data.complete_label,
processing_information_label = data.processing_information_label,
motivation_label = data.motivation_label,
action_label = data.action_label,
other_data_label = data.other_data_label,
//Data comming from wevsite.views//
team_name_list2 = data.team_name_list2
info_array = data.info_array
current_user = data.current_user
team_list_id = data.team_list_id
fixed_array = info_array[current_user]
function random_color(){
var color = 'rgba(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256))+ ',' + 0.2 + ')';
return color
}
//ctx//
var ctx2 = document.getElementById("info_process").getContext('2d');
//graph 2//
var info_process = new Chart(ctx2,{
type: 'radar',
data: {
labels: processing_information_label,
datasets:[{
data: fixed_array, //processing_information_data,
backgroundColor: random_color()
},
{
backgroundColor: random_color(),
data: []
}]
},
options: {
legend: {
position: 'top',
display: false
},
scale: {
display: true,
ticks: {
beginAtZero: true,
}
},
responsive:true,
maintainAspectRatio: true,
}
});
//end graph 2//
$(".pick-chart").change(function (e) {
e.preventDefault();
var val = $(this).val();
if (val != 0) {
$.ajax({
method: "GET",
url: endpoint,
success: function(data){
console.log(data)
//Labels coming from website.views//
info_array = data.info_array
current_user = data.current_user
config.data.datasets[0].data = info_array[val];
config.data.datasets[1].data = info_array[current_user];
mainChart.update();
}
});
} else {
config.data.datasets[0].data = [];
}
mainChart.update();
});
}
})
</script>
If you format your dropdown box as such: (so the user_id in the value of each option)
<select name="pick-chart" class="pick-chart">
<option value="6">Raphael</option>
...
</select>
You could rewrite your pick-chart.change function to something like:
$(".pick-chart").change(function (e) {
e.preventDefault();
var val = $(this).val();
if (val != 0) {
$.ajax({
method: "GET",
url: endpoint,
success: function(data){
console.log(data)
//Labels coming from website.views//
info_array = data.info_array
current_user = data.current_user
config.data.datasets[0].data = info_array[val];
config.data.datasets[1].data = info_array[current_user];
mainChart.update();
}
});
} else {
config.data.datasets[0].data = [];
}
mainChart.update();
});
Assuming your data really is dynamic and could change while the user stays at your page. Also assuming that you want to compare current_user (which should also be a user_id) in dataset 1, like your fixed data, to a selected other user in dataset 0.

Chart.js donut chart remains grey - no color

I have a donut chart being created by chart.js as follows:
<div id="chartContainer" style="height: 320px; width: 320px">
<canvas id="hoursFEContainer"></canvas>
</div>
I require chart.js as follows (downloaded from npm):-
require('chart.js');
Then in a relevant function I instantiated Chart.js as follows:-
var distinctFeeEarners = ['MEH', 'IHM'];
var totalHoursByFE = [0.8, 0.7];
var chartdata = {
labels: distinctFeeEarners,
datasets : [
{
label: 'Fee Earner',
data: totalHoursByFE
}
]
};
var ctx = $("#hoursFEContainer");
var donutChart = new Chart(ctx, {
type: 'doughnut',
backgroundColor:
['rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)'],
data: chartdata
});
The chart displays with the correct data, but the donut does not have any colours?
Whats wrong?
EDIT: Beyond stupid, backgroundColor needs to be in datasets not in new Chart. Nevermind.
The reason is that you define backgroundColor at the wrong place. It's a dataset property, hence needs to be defined inside the dataset.
var distinctFeeEarners = ['MEH', 'IHM'];
var totalHoursByFE = [0.8, 0.7];
var chartdata = {
labels: distinctFeeEarners,
datasets: [{
label: 'Fee Earner',
data: totalHoursByFE,
backgroundColor: ['rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)']
}]
};
var donutChart = new Chart(document.getElementById('hoursFEContainer'), {
type: 'doughnut',
data: chartdata
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<div id="chartContainer" style="height: 320px; width: 320px">
<canvas id="hoursFEContainer"></canvas>
</div>
Had exactly the same problem with ng2-charts
What did it for me was not pre-initializing dataset.
Prevously i would declare empty array
public data: MultiDataSet = [];
then after backend request resolves i would assign new value
const dataset: Array<number> = new Array();
response.items.map(result => {
dataset.push(result);
});
this.data = [dataset];
This would print doughnut chart but without color. Everything was gray.
Simply not preinitializing MultiDataSet like this fixes things
public data: MultiDataSet; //=[];

Categories