C3 donut chart with data from JSON object - javascript

I'm attempting to create a C3 donut chart using data from a JSON object stored in a variable. The title renders correctly but the columns don't. If I hard code the column data (see commented out line) the chart renders but if I try to parse the column data from a JSON object it fails. However when I console log the column data ( in variable 'theatres'), it looks correct.
const txt = '{"theatres":"[[\'AMER INT\',386],[\'AMER US\',464],[\'APAC\',914],[\'EMEA\',706],[\'JP\',81]]","title":"94 Countries"}';
const dataobj = JSON.parse(txt);
var theatres = dataobj.theatres;
var title = dataobj.title;
console.log(dataobj);
console.log(theatres);
var chart = c3.generate({
bindto: '#chart',
data: {
type: 'donut',
// columns: [['AMER INT',386],['AMER US',464],['APAC',914],['EMEA',706],['JP',81]]
columns: theatres
},
size: {
height: 800
},
donut: {
title: title
}
});
What am I missing?
Thanks in advance!

The problem is that the value of theatres is still string:
"[['AMER INT', 386], ['AMER US', 464], ['APAC', 914], ['EMEA', 706], ['JP', 81]]"
So you need to use eval() to evaluate as valid array
const txt = '{"theatres":"[[\'AMER INT\',386],[\'AMER US\',464],[\'APAC\',914],[\'EMEA\',706],[\'JP\',81]]","title":"94 Countries"}';
const dataobj = JSON.parse(txt);
var theatres = dataobj.theatres;
var title = dataobj.title;
//console.log(dataobj);
//console.log(theatres);
var chart = c3.generate({
bindto: '#chart',
data: {
type: 'donut',
columns: eval(theatres)
},
size: {
height: 350
},
donut: {
title: title
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.10.0/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/c3/0.7.20/c3.min.js"></script>
<div id="chart"></div>

Related

c3 js pie chart from csv

I'm trying to display a pie chart using C3.js loading data from a CSV. I'm able to get the chart to display my data when it's manually input. But I can't figure out how to get the chart to load properly from the CSV. Is there a way to tell the pie chart that the first column is a label and the second column is the data to be displayed from the CSV?
Here's where I'm at:
var summary = c3.generate({
bindto: '#chart',
data: {
columns: [
['0-1',42.11],
['1-3',33.80],
['3-5',6.94],
['5-10',3.99],
['10-2',10.05],
['>20',3.11]
],
type: 'pie'
},
size: {
width: 500,
height: 500
}
})
setTimeout(() => {
c3.generate({
bindto: '#chart',
data: {
url: 'data.csv',
type: 'pie'
},
size: {
width: 500,
height: 500
}
});
}, 1000)
My CSV
Name,Percentage
0-1,42.11
1-3,33.80
3-5,6.94
5-10,3.99
10-20,10.05
>20,3.11
What the chart is supposed to look like:
https://i.stack.imgur.com/koymo.png
How it's loading from the CSV:
https://i.stack.imgur.com/bFmLc.png
Figured it out. I used Papaparse to parse the CVS data into the correct format. Here's how to display a pie chart from a CSV using C3.js (also had to change columns to rows):
function parseData(createGraph) {
Papa.parse("data.csv", {
download: true,
complete: function(results) {
createGraph(results.data);
}
});
}
function createGraph(data) {
var name = [];
var percentage = [];
for (var i = 0; i < data.length; i++) {
name.push(data[i][0]);
percentage.push(data[i][1])
}
console.log(name);
console.log(percentage);
var summary = c3.generate({
bindto: '#chart',
data: {
rows: [
name,
percentage
],
type: 'pie'
},
legend: {
show:false
}
});
}
parseData(createGraph);

Auto Generating Pie Chart Legend

I am trying to create a pie chart in JavaScript. I would like this chart to display in the legend only the labels that are non zero.
Does anyone have any ideas how this can be done?
Here is the code I have so far. Currently the legend of the pie chart shows all possible 12 Labels, even though 8 of these have zero value. "Data" will eventually be filled from a database and therefore it is important that this is an automated process.
var ctx = document.getElementById("myPieChart");
var myPieChart = new Chart(ctx, {
type: 'pie',
data: {
labels: ["Astronomica", "Deuteronic", "Floral", "Galactic","Celestrial","Heliosphere","Jupiter","Interstella","Koronis","Eclipse,"Borealis","Lunatic"],
datasets: [{
data: [12.21, 15.58, 11.25, 8.32],
backgroundColor: ['#007bff', '#dc3545', '#ffc107', '#28a745'],
}],
},
});
You can manage data before use they.
var ctx = document.getElementById("myPieChart");
var input_lables = ["Astronomica" , "Deuteronic", "Floral", "Galactic", "Celestrial", "Heliosphere", "Jupiter", "Interstella","Koronis", "Eclipse", "Borealis", "Lunatic"];
var input_values = [12.21, 15.58, 11.25, 8.32];
var output_lables = [];
var output_values = [];
for(var i=0;i<input_lables.length;i++){
if(!values[i]){
output_lables.push(input_lables[i]);
output_values.push(input_values[i]);
}
}
var myPieChart = new Chart(ctx, {
type: 'pie',
data: {
labels: output_lables,
datasets: [{
data: output_values,
backgroundColor: ['#007bff', '#dc3545', '#ffc107', '#28a745'],
}],
},
});
if you went to automatic it just enough make a function like this code.
According with the documentation you can use the filter parameter in the label
http://www.chartjs.org/docs/latest/configuration/legend.html
and you can make a validation to validate the data and if it is 0 you can return false
Filter a legend Item with Chartjs.org V2.7

Pie chart isn't loading, but the labels are

I'm using Chart.js in Laravel to display data.
I'm following this tutorial, which worked for the bar chart. But now I'm trying a pie chart.
This is my controller which gets the data.
public function chart()
{
$result = \DB::table('users')
->where('userType','=','Landlord')
->orderBy('created_at', 'ASC')
->get();
return response()->json($result);
}
The view is this
<script>
var url = "{{url('/users')}}";
var Name = new Array();
var Email = new Array();
$(document).ready(function(){
$.get(url, function(response){
response.forEach(function(data){
Name.push(data.name);
Email.push(data.email);
});
var ctx = document.getElementById("canvas").getContext('2d');
var myPieChart = new Chart(ctx,{
type: 'pie',
data : {
datasets: [{
data: [Name,Email]
}],
// These labels appear in the legend and in the tooltips when hovering different arcs
labels: [Name, Email]
}
});
});
});
</script>
This is the output
According to the ChartJS documenation, the expected data passed for a pie chart is numbers only. Here's an example of a dataset that should work:
data = {
datasets: [{
data: [10, 20, 30]
}],
// These labels appear in the legend and in the tooltips when hovering different arcs
labels: [
'Red',
'Yellow',
'Blue'
]
};
Currently, your Ajax request is getting the name and email from the /users route; you will need to update the request to get some sort of number value from /users and add that to the dataset.

Pushing data from json to Chart.js labels and data

I am using the Chart.js lib to make charts.
I have a json array that I am getting from a database.
Here is the console log of it: Data
I need to get the address, speed, and speed limit for every element in the list and use it in a chart.
My current code is as follows:
function ShowChart() {
var popCanvas = document.getElementById("speedLimitsChart");
console.dir(speeddata);
var labels = speeddata.map(function (e) {
return e.Adress;
});
var speed = speeddata.map(function (e) {
return e.Speed;
});
var speedlimits = speeddata.map(function (e) {
return e.SpeedLimits;
});
console.dir(labels);
var barChart = new Chart(popCanvas, {
type: 'bar',
data: {
datasets: [{
label: 'Speed',
data: speed,
backgroundColor: '#1E90FF'
}, {
label: 'Speed Limits',
data: speedlimits,
backgroundColor: '#B22222',
type: 'line'
}],
},
labels: labels
});
}
But in the result I only have the first element in my chart, and there are no labels.
Here is the output screen: Chart
I checked speed, speedlimits and labels and all of them have 2 elements. Can you please advise where my problem might be?
I found where is my problem
I need to write labels inside of data
Like this
var barChart = new Chart(popCanvas, {
type: 'bar',
data: {
labels: labels ,
datasets: [{
label: 'Speed',
data: speed,
backgroundColor: '#1E90FF'
}, {
label: 'Speed Limits',
data: speedlimits,
backgroundColor: '#B22222',
type: 'line'
}],
},
});

Problem showing data from a csv file for highcharts

I am trying to create a highchart line graph using data from a .csv file. But my webpage is just showing the titles of x and y axis, but no data. The code is as follows:
$(document).ready(function() {
var c = [];
var d = [];
$.get('data.csv', function(data) {
alert("data in the file: " + data);
var lines = data.split('\n');
$.each(lines, function(lineNo, line) {
var items = line.split(',');
c.push(items[0]);
d.push(parseInt(items[1]));
});
});
var options = {
chart: {
renderTo: 'chart',
defaultSeriesType: 'line'
},
title: {
text: 'Weight Monitor'
},
xAxis: {
title: {
text: 'Date Measured'
},
categories: c
},
yAxis: {
title: {
text: 'Weight (in Lbs)'
}
},
series: [{
data: d
}]
};
var chart = new Highcharts.Chart(options);
});
i tried to print the data read from file on screen just to check if the file was read properly and i got the proper data, but still my graph is not showing anything.
following is the data in my csv file:
2011-08-01 00:00:00,155
2011-08-02 00:00:00,156
2011-08-03 00:00:00,157
2011-08-03 00:00:00,160
where left value is date to be shown in x axis and right value is reading points for graph.
any help will be thankful.
Your code works perfect.
<script type="text/javascript">
$(document).ready(function() {
var c = [];
var d = [];
$.get('data.csv', function(data) {
var lines = data.split('\n');
$.each(lines, function(lineNo, line) {
var items = line.split(',');
c.push(items[0]);
d.push(parseInt(items[1]));
});
});
var options = {
chart: {
renderTo: 'chart',
defaultSeriesType: 'line'
},
title: {
text: 'reading'
},
xAxis: {
title: {
text: 'Date Measurement'
},
categories: c
},
yAxis: {
title: {
text: 'reading'
}
},
series: [{
data: d
}]
};
var chart = new Highcharts.Chart(options);
});
</script>
Copy this whole code and save it as .html file in a directory and create the data.csv file in the same directory and make sure that there no empty lines, no spaces where they are not needed and no line-break at the end.
And then open the .html file, the chart should show up with the right data.
Add the chart within $.get.
Note that we can't create the chart outside the Ajax callback, as we have to wait for the data to be returned from the server. See this.
$.get('data.csv', function(data) {
var lines = data.split('\n');
$.each(lines, function(lineNo, line) {
var items = line.split(',');
c.push(items[0]);
d.push(parseInt(items[1]));
});
var chart = new Highcharts.Chart(options);
},'Text');
Also mention explicitly the data return type to "Text" which might be a problem some time.
You must read the documentation properly. See http://www.highcharts.com/documentation/how-to-use#preprocessing
They already have a demo of the csv http://highcharts.com/studies/data-from-csv.htm .
Please go through the docs and familiarise yourself ! .

Categories

Resources