ChartJS not displaying properly in AJAX called page - javascript

I am using the latest version of chart JS (2.5.0) and trying to get 2 polar area charts to appear in a page that has the content of the page loaded in VIA ajax. Here are my two polar charts (I will omit the rest of the code as it is not pertinent to this):
<canvas id="myChart"></canvas>
<script>
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'polarArea',
options: {
responsive: true
}
data: {
labels: ["Head", "Chest", "Stomach", "Left Arm", "Right Arm", "Left Leg", "Right Leg"],
datasets: [{
backgroundColor: [
"#1AFF05",
"#0D9900",
"#197011",
"#1E4A1A",
"#4C4D4C",
"#81917F",
"#B5F7B0"
],
data: <?php getHitBoxPercents($player);?>
// data: [12, 19, 3, 17, 28, 24, 7]
}]
}
});
</script>
And Chart 2:
<canvas id="myChart1v1"></canvas>
<script>
var ctx1v1 = document.getElementById("myChart1v1").getContext('2d');
var myChart1 = new Chart(ctx1v1, {
type: 'polarArea',
options: {
responsive: true
}
data: {
labels: ["Head", "Chest", "Stomach", "Left Arm", "Right Arm", "Left Leg", "Right Leg"],
datasets: [{
backgroundColor: [
"#1AFF05",
"#0D9900",
"#197011",
"#1E4A1A",
"#4C4D4C",
"#81917F",
"#B5F7B0"
],
data: <?php getHitBoxPercents($player);?>
// data: [12, 19, 3, 17, 28, 24, 7]
}]
}
});
</script>
These are both in Tab menus which all works fine but here are the weird things:
The first chart doesn't load properly at all, it loads the "outline" of the chart but no data, although the data is all set properly in the javascript and it works just fine if I take away the second chart. See picture: Puush Image
The chart from the second bit of code works perfectly: Puush Image 2
If I press the button to generate the ajax again (a form with a search button to find matching records) The first chart goes away completely (code is all still there) and the second chart still works just fine. Puush example of this
Maybe the key to this whole thing: If I resize the page the chart appears, regardless of if I reload the ajax in the page and the chart all disappears all I have to do is resize the page (go to half size then maximize again) and it works, both charts. I don't know why or how to fix this but I don't want that to be the only solution.
EDIT: I am trying to fix mine according to this fiddle but it isn't working: fiddle The new code I am trying to use:
$(function(){
var chart_polar_options = {
responsive: true
};
var data1v1 = {
labels: ["Head", "Chest", "Stomach", "Left Arm", "Right Arm", "Left Leg", "Right Leg"],
datasets: [{
backgroundColor: [
"#1AFF05",
"#0D9900",
"#197011",
"#1E4A1A",
"#4C4D4C",
"#81917F",
"#B5F7B0"
],
data: <?php getHitBoxPercents($player);?>
}]
};
var ctx1v1 = document.getElementById("myChart1v1").getContext('2d');
var myChart1 = new Chart(ctx1v1, {
type: 'polarArea',
options: {
responsive: true
},
data: data1v1
});
$('#tab2').on('shown.bs.tab', function (e) {
myChart1.destroy();
myChart1 = new Chart(ctx1v1, {
type: 'polarArea',
options: {
responsive: true
},
data: data1v1
});
});
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'polarArea',
options: {
responsive: true
},
data: data1v1
});
$('#tab1').on('shown.bs.tab', function (e) {
myChart.destroy();
myChart = new Chart(ctx, {
type: 'polarArea',
options: {
responsive: true
},
data: data1v1
});
});
});
The problem with the code above is neither load until I resize the browser but it is pulling in the charts, they just look blank.

Related

Any suggestion on how to override Chart JS Donut library

I have added a donut chart as shown below without the numbers.
I wanted to make the outer-border fixed like the first picture shown below and hide the inner border and I have used Chart JS.
Any way I can do that as the chart JS default there is only border-color?
var ctx = document.getElementById('freeChart');
var myChart = new Chart(ctx, {
type: 'doughnut',
data: {
datasets: [{
data: [30,70],
backgroundColor: ['#9f9fa6'],
borderColor: ['#9f9fa6','#9f9fa6'],
}],
},
options:{
cutoutPercentage: 80,
elements: {
arc: {
borderWidth: 1
}
}
}
});

How to display grouped data in ChartJs

I have the following array:
Where the arrays keys are the dates and the only element I want to plot, of each set, is the weight. Look:
I am putting the code as follows. Notice that I am already grouping in the date attribute the whole set belonging to each that key.
var ctx = document.getElementById("barChart").getContext("2d");
var data = {
labels: ['21/03/2018','01/04/2018','02/04/2018','04/04/2018','05/04/2018','06/04/2018'],
datasets: [
{
label: '21/03/2018',
data: [12, 0, 0]
},
{
label: '01/04/2018',
data: [15.00, 15.00,15.00]
},
{
label: '02/04/2018',
data: [25.00, 25.00, 25.00]
},
{
label: '04/04/2018',
data: [25.00, 25.00, 25.00]
},
{
label: '05/04/2018',
data: [-8.14,-7.93, -7.84]
},
{
label: '06/04/2018',
data: [-35.9 ,-38.1, -37.5]
},
]
};
var myBarChart = new Chart(ctx, {
type: 'bar',
data: data,
});
But in this way ChartJs does not understand that it only needs to plot the data set present in the "data" attribute and grouping them by the key. Plotting the graph in the wrong way.
How could I plot the data correctly knowing that they are already grouped?
You need to organize your data as such:
var ctx = document.getElementById("canvas").getContext("2d");
var data = {
labels: ['21/03/2018','01/04/2018','02/04/2018','04/04/2018','05/04/2018','06/04/2018'],
datasets: [
{
data: [12, 15.00, 25.00, 25.00, -8.14, -35.9]
},{
data: [0, 15.00, 25.00, 25.00, -7.93, -38.1]
},{
data: [0, 15.00, 25.00, 25.00, -7.84, -37.5]
}
]
};
var myBarChart = new Chart(ctx, {
type: 'bar',
data: data,
options:{
legend: 'none'
}
});
I took your legend out as it's useless in this case. To look at it in the coding persepective, whatever index the date in labels is at needs to correlate with the index of the information you want to display in that grouping. data[0] refers to labels[0] and so on.

Use JSON file with chart.js

I've been looking all over chart.js-related questions, but not two developers seem to be giving the same answer on how to display a chart using chart.js + JSON.
I am trying to display a chart using a JSON file - specifically a list of "amounts" with their relative labels ("January 2017",...).
The chart canva display just fine, no console log error, but no chart itself. What am I missing?
Thanks!
Here my chart.js code:-
var labels = [];
var data = [];
$.getJSON("https://jsonblob.com/api/jsonBlob/26078b70-6b6f-11e7-a38a-bf689f57642c"), function (data) {
$.each(data.customers.amounts, function(key, value){
var labels = json.map(function(item) {
labels.push(item.key);
});
var data = json.map(function(item) {
data.push(item.value);
});
});
}
var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
type: 'line',
data: {
datasets: [{
labels: labels,
backgroundColor: 'rgb(129, 198, 2228)',
borderColor: 'rgb(0, 150, 215)',
data: data
}]
},
options: {
responsive: 'true',
}
});
and here's my JSON file:-
{
"customers": [
{
"first_name": "John",
"last_name": "Doe",
"account": "123456",
"period": "13th July - 13th August",
"due_date": "14th September",
"amounts": [
["January 2017", 121.23],
["February 2017", 145.23],
["March 2017", 55.12],
["April 2017", 78.58],
["May 2017", 89.13],
["June 2017", 45.78],
["July 2017", 90.22]
]
}
]
}
Couple of Issues :
since $.getJSON() method is asynchronous, you should construct the chart inside it­'s callback function.
you are looping through the response data incorrectly. could be as simple as :
­
var labels = data.customers[0].amounts.map(function(e) {
return e[0];
});
var data = data.customers[0].amounts.map(function(e) {
return e[1];
});
you are adding labels array to your dataset, while it belogns to the data object.
Here is the revised version of your code :
$.getJSON("https://jsonblob.com/api/jsonBlob/26078b70-6b6f-11e7-a38a-bf689f57642c", function(data) {
var labels = data.customers[0].amounts.map(function(e) {
return e[0];
});
var data = data.customers[0].amounts.map(function(e) {
return e[1];
});
var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
type: 'line',
data: {
labels: labels,
datasets: [{
backgroundColor: 'rgb(129, 198, 2228)',
borderColor: 'rgb(0, 150, 215)',
data: data
}]
},
options: {
responsive: 'true',
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="myChart"></canvas>

charts.js not updating after ajax request

I'm a complete newb with js and jquery but have muddled my way through getting a chart to properly display using Flask and an Ajax request. Where I'm having a problem is getting the charts data to refresh. I can get the chart to display just fine if I create it as a new chart as shown in the code below
$(document).ready(function() {
var getdata = $.post('/charts');
var ctx = document.getElementById('myChart').getContext('2d');
var myChart
getdata.done(function(results){
var chartData = {
labels: results['month'],
datasets: [{
label: 'Debits',
data: results['debit'],
backgroundColor: "rgba(153,255,51,0.4)"
}, {
label: 'Credits',
data: results['credit'],
backgroundColor: "rgba(255,153,0,0.4)"
}, {
label: 'Balance',
data: results['balance'],
backgroundColor: "rgba(50,110,0,0.4)"
}]
}
myChart = new Chart(ctx, {type: 'line', data: chartData});
});
$("form :input").change(function() {
year = $(this).val();
console.log(year)
$.ajax({
type: "POST",
url: "/data",
data: {'year':year},
success: function(results){
var updatedData = {
labels : results['month'],
datasets : [{
label: 'Debits',
data: results['debit'],
backgroundColor: "rgba(153,255,51,0.4)"
}, {
label: 'Credits',
data: results['credit'],
backgroundColor: "rgba(255,153,0,0.4)"
}, {
label: 'Balance',
data: results['balance'],
backgroundColor: "rgba(50,110,0,0.4)"
}]
}
myChart= new Chart(ctx, {type: 'line', data: updatedData});
}
});
});
});
But if I change the last line to
myChart.update(updatedData)
nothing happens, I don't get any errors, the chart doesn't update. Nothing. The strange thing is that I know the myChart is global because I don't have to create it again after the Ajax request.
Thanks
From the documentation of charts.js (http://www.chartjs.org/docs/#getting-started-creating-a-chart), you first need to change data and then call update (arguments for update function are not the data, but duration etc.):
.update(duration, lazy)
Triggers an update of the chart. This can be safely called after replacing the entire data object. This will update all scales, legends, and then re-render the chart.
// duration is the time for the animation of the redraw in milliseconds
// lazy is a boolean. if true, the animation can be interrupted by other animations
myLineChart.data.datasets[0].data[2] = 50; // Would update the first dataset's value of 'March' to be 50
myLineChart.update(); // Calling update now animates the position of March from 90 to 50.
So in your case:
myChart.data = updatedData;
myChart.update();

How to display "%" sign on mouse hover in Pie-Chart

I am drawing graph on UI using ChartJS 2.0. And I am able to render a Pie Chart. But I want the mouse-hover to show the data along with a "%" sign. How can I append % So if on mouse hover I am getting Rented: 93 I would like to see Rented: 93 %. Kindly guide me.
Below is what I have now:
var sixthSubViewModel = Backbone.View.extend({
template: _.template($('#myChart6-template').html()),
render: function() {
$(this.el).html(this.template());
var ctx = this.$el.find('#pieChart')[0];
var data = {
datasets: [{
data: this.model.attributes.currMonthOccAvailVac,
backgroundColor: [
"#455C73",
"#BDC3C7",
"#26B99A",
],
label: 'My dataset' // for legend
}],
labels: [
"Rented",
"Vacant",
"Unavailable",
]
};
var pieChart = new Chart(ctx, {
type: 'pie',
data: data
});
},
initialize: function(){
this.render();
}
});
Understanding:
I understand that currently hover takes the label and adds a colon and then adds data to it. So if label = Rented, Data = 93 I will see something like Rented: 93 on mouse-hover. How can I change text of mouse-hover to display Rented: 93%. Below is the image of what I have till now on mouse-hover.
I understand that I need to add one "options" in the pie chart. But I am not sure how to do that. Please help me.
You can edit what is displayed in your tooltip with the callbacks.label method in your chart options, and then simply add a "%" to the default string using :
tooltipItems -- See documentation for more information (scroll up a bit to "Tooltip Item Interface")
data -- Where the datasets and labels are stored.
var ctx = document.getElementById("canvas");
var data = {
datasets: [{
data: [93, 4, 3],
backgroundColor: [
"#455C73",
"#BDC3C7",
"#26B99A",
],
label: 'My dataset' // for legend
}],
labels: [
"Rented",
"Vacant",
"Unavailable",
]
};
var pieChart = new Chart(ctx, {
type: 'pie',
data: data,
options: {
tooltips: {
callbacks: {
label: function(tooltipItems, data) {
return data.labels[tooltipItems.index] +
" : " +
data.datasets[tooltipItems.datasetIndex].data[tooltipItems.index] +
' %';
}
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.2.1/Chart.min.js"></script>
<canvas id="canvas" height="150"></canvas>

Categories