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>
Related
I am trying to draw a two-line chart with two datasets that share the same labels using chart.js on my ASP.NET MVC app.
I am only getting the data from "Value" plotted on the chart and not "Age" and I cannot find the reason why.
Relevant Controller code:
public ActionResult GetLineChartData()
{
List <LineChartData> dataForLineChart = new List <LineChartData> ();
dataForLineChart.Add(new LineChartData {
Date = DateTime.NOW, Value = 100, Age = 20
});
return Json(dataForLineChart, JsonRequestBehavior.AllowGet);
}
Relevant View code:
$.ajax({
type: "Post",
url: '#Url.Action("GetLineChartData", "Posts")',
contentType: false,
processData: false,
data: dataFromForm,
dataType: "json",
traditional: true,
success: function (data) {
console.log(data);
var labels = data.map(function (e) {
return e.Date;
});
var data = data.map(function (e) {
return e.Value;
});
var data2 = data.map(function (e) {
return e.Age;
});
var ctx = scatterChart.getContext('2d');
var config = {
type: 'line',
data: {
labels: labels,
datasets: [{
label: "Test"
data: data,
backgroundColor: 'rgba(0, 119, 204, 0.3)'
},
{
label: "Test",
data: data2,
backgroundColor: 'rgba(242, 204, 143, 1)'
}
]
}
};
}
});
(Some code I do not consider important is hidden)
Issue & Concern
Because the below line overwrites the original data value.
var data = data.map(function (e) {
return e.Value;
});
After the above line, now the data array was overwritten as an array of integers instead of an array of objects. Based on your sample response from API, the current value of data will be: [100].
var data2 = data.map(function (e) {
return e.Age;
});
From the above line, it can't find the Age property in the element. Hence the result of data2 will be: [undefined].
This is why the data2 is not rendered in the chart.
Solution
Create another variable for the data transformation to avoid overwriting the existing data value.
var dataset = data.map(function (e) {
return e.Value;
});
var dataset2 = data.map(function (e) {
return e.Age;
});
var config = {
type: 'line',
data: {
labels: labels,
datasets: [
{
label: 'Test',
data: dataset,
backgroundColor: 'rgba(0, 119, 204, 0.3)',
},
{
label: 'Test',
data: dataset2,
backgroundColor: 'rgba(242, 204, 143, 1)',
},
],
},
};
Demo # StackBlitz
I'm doing a project which is to extract data from python and show it in jsp dashboard.
I'm trying to load a json file to chartjs but it's not giving result
<script>
$.getJSON("resources/json_test.json", function(data) {
var labels = data.department.map(function(e) {
return e[1];
});
var data = data.volunteer.map(function(e) {
return e[1];
});
var context = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(context, {
type : 'bar',
data : {
labels : labels,
datasets : [ {
label : 'volunteer',
lineTension : 0.1,
data : data,
backgroundColor : "rgba(255, 99, 132, 0.2)"
}]
}
});
});
{"department":{"0":"IT","1":"Math","2":"English","3":"Software","4":"Game"},"volunteer":{"0":409,"1":1781,"2":476,"3":550,"4":562}}
To call .map() the datastructure needs to be an array, and since yours are objects it aint working, if you change your code to this it should work:
const labels = Object.values(data.department)
const parsedData = Object.values(data.volunteer)
const context = document.getElementById('myChart').getContext('2d');
const myChart = new Chart(context, {
type: 'bar',
data: {
labels: labels,
datasets: [ {
label: 'volunteer',
lineTension: 0.1,
data: parsedData,
backgroundColor: "rgba(255, 99, 132, 0.2)"
}]
}
});
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.
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>
I am generating a pie chart from data stored in JSON format. I am trying to change color according to the JSON value.
Ex : if value # json[0]['data'][0][0] = "FAILED" //setColor(RED).
I was able to set the color for column stack charts using options.series.color, however when I tried to use this option with pie chart its converting data into series and unable to render the chart on a container.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
function getData(id) {
$.getJSON("pie.php", {
id: id
}, function(json) {
option.series = json;
chart = new Highcharts.chart(options);
});
}
</script>
can we set the color in getData function only before calling 'chart' or do i need to use Highcharts.setOptions() and define the color codes.
The better option is to create series based on your json data. This is how you can do to specify color based on data.
var serie = {
data: []
};
var series = [serie];
jQuery.each(jsonData, function(index, pointData) {
var point = {
name: pointName,
y: pointData.Value,
color: pointData.Value == 'FAILED' ? 'ff0000' : '00ff00',
serverData: pointData
};
serie.data.push(point);
});
chart.series = series;
OR
Have a look at this easier version
JSFiddle
$( document ).ready(function() {
var data = [{
"name": "Tokyo",
"data": 3.0
}, {
"name": "NewYork",
"data": 2.0
}, {
"name": "Berlin",
"data": 3.5
}, {
"name": "London",
"data": 1.5
}];
// Highcharts requires the y option to be set
$.each(data, function (i, point) {
point.y = point.data;
point.color = parseFloat(point.data) > 3 ? '#ff0000' : '#00ff00';
});
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'pie'
},
series: [{
data: data
}]
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<div id="container" style="height: 300px"></div>
we can set highchart custom color by setOption function which is as
Highcharts.setOptions({
colors: ['#F64A16', '#0ECDFD',]
});
It sets color to my pie chart.
Another solution for dynamic 3D color
Actually this customization for theme selection Here it is
3 colors sets to color variable
var colors = Highcharts.getOptions().colors;
$.each(colors, function(i, color) {
colors[i] = {
linearGradient: { x1: 0, y1: 0, x2: 1, y2: 0 },
stops: [
[0, '#0ECDFD'],
[0.3, '#F64A16'],
[1, color]
]
};
});
& assign directly in series
{
type : 'column',
name : 'bug',
data : [],
color : colors,
pointWidth : 28,
}