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);
Related
I have a line chart like this:
The tooltips are not showing.
Here is what initializes the chart:
function initializeLineChart() {
var graph = document.getElementById('LineChart').getContext('2d');
var chart = new Chart(graph, {
type: "line",
data: LineUserData,
options: {
tooltips: {
mode: 'label'
}
}
});
}
LineUserData is something like this:
LineUserData = {
labels: ["Janeiro","Fevereiro","Março","Abril","Maio","Junho","Julho","Agosto","Setembro","Outubro","Novembro","Dezembro"],
datasets: [{"label":"Loja 2","backgroundColor":"#1C154A16","borderColor":"#1C154A","borderWidth":0,"pointBorderColor":"#1C154A16","pointBackgroundColor":"#1C154A","data":[0,12,0,2,1,0,1,0,0,0,0,0]},{"label":"Sem Vendedor","backgroundColor":"#36388A16","borderColor":"#36388A","borderWidth":0,"pointBorderColor":"#36388A16","pointBackgroundColor":"#36388A","data":[0,0,0,0,0,0,0,0,0,0,0,0]}],
}
It appears this error on the console:
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>
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'
}],
},
});
Right now I have a simple column chart with following code using Highcharts:
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
type: 'column'
},
title: {
//some code
},
xAxis: {
categories: []
},
yAxis: {
//some code
},
plotOptions: {
series: {
borderWidth: 0,
dataLabels: {
enabled: true,
format: '{point.y}'
}
}
},
legend: {
//some code
},
series: []
};
$.getJSON("data/column.php", function(json) {
options.xAxis.categories = json[0]['data'];
options.series[0] = json[1];
chart = new Highcharts.Chart(options);
});
});
I now want to add a line chart to the same container, using exactly the same options (despite of the chart type). The date is also served via JSON.
How can I achieve this?
What I did so far:
I created a second variable "options2" with values chart and series.
Then I called
$.getJSON("data/line.php", function(json) {
options.xAxis.categories = json[0]['data'];
options2.series[1] = json[1];
chart = new Highcharts.Chart(options2);
});
But that only shows the first column chart.
Probably you should try use $.merge to prevent object edition.
Try this
$.getJSON("data/column.php", function(json) {
// Merge objects
var newOptions = $.extend({}, options);
// Edit new object instead of old
newOptions.xAxis.categories = json[0]['data'];
newOptions.series[0] = json[1];
chart = new Highcharts.Chart( newOptions );
});
Solved it by passing the series option (chart type) directly via JSON.
I added the "type:line" to the data array, which then overrides previously set options within the script tag.
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 ! .