How do I import a csv into chart.js? - csv

I have been looking for this solution but can't seem to find it . Does chart.js support this ?
I have attempted to parse in the data with papaparse, but due to my limited knowledge I can't find a solution.

There is a Chart.js plugin chartjs-plugin-datasource that makes it easy to load data from CSV files.
Let's suppose you have a CSV file as shown below, and it is saved as sample-dataset.csv in the same directory as your HTML file:
,January,February,March,April,May,June,July
Temperature,7,7,10,15,20,23,26
Precipitation,8.1,14.9,41.0,31.4,42.6,57.5,36.0
Include Chart.js and chartjs-plugin-datasource in your page:
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.8.0"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datasource#0.1.0"></script>
<canvas id="myChart"></canvas>
Then, specify sample-dataset.csv in your script. By default, each row in a CSV file will be mapped to one dataset, and the first column and the first row will be treated as dataset labels and index labels respectively. You can also customize how to parse CSV data using options.
var ctx = document.getElementsById("myChart");
var chart = new Chart(ctx, {
type: 'bar',
data: {
datasets: [{
type: 'line',
yAxisID: 'temperature',
backgroundColor: 'transparent',
borderColor: 'rgb(255, 99, 132)',
pointBackgroundColor: 'rgb(255, 99, 132)',
tension: 0,
fill: false
}, {
yAxisID: 'precipitation',
backgroundColor: 'rgba(54, 162, 235, 0.5)',
borderColor: 'transparent'
}]
},
plugins: [ChartDataSource],
options: {
scales: {
yAxes: [{
id: 'temperature',
gridLines: {
drawOnChartArea: false
}
}, {
id: 'precipitation',
position: 'right',
gridLines: {
drawOnChartArea: false
}
}]
},
plugins: {
datasource: {
url: 'sample-dataset.csv'
}
}
}
});

Here is my solution that works fine for me. I have a CSV file like this:
country,population
China,1415046
India,1354052
United States,326767
Indonesia,266795
Brazil,210868
...
I want to plot a bar chart with my dataset, the y-axis is population and the x-axis is country.
This is the body of my HTML file.
<body>
<canvas id="myChart" width="100" height="100"></canvas>
<script>
// Load the dataset
d3.csv("data.csv").then(makeChart);
// Plot the data with Chart.js
function makeChart(countries) {
var countryLabels = countries.map(function (d) {
return d.country;
});
var populationData = countries.map(function (d) {
return d.population;
});
var chart = new Chart("myChart", {
type: "bar",
data: {
labels: countryLabels,
datasets: [
{
data: populationData
}
]
}
});
}
</script>
</body>
Result:
You can try it with Codesandbox.

I've had need to do something like this from time to time as well. Here's a link on how to create a chart with Chart.js from a CSV file that explains exactly how to create a chart with Chart.js directly from a CSV file.
The use case explains how to convert a CSV file to JSON using the Flex.io web service (Full disclosure: I'm the senior front end developer at Flex.io).
Here's a JsFiddle if you'd like to see the use case in action:
function getRandomColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
$.ajax({
type: 'post',
url: 'https://www.flex.io/api/v1/pipes/flexio-chart-js-csv-to-json/run?stream=0',
beforeSend: function(xhr) {
xhr.setRequestHeader('Authorization', 'Bearer nmgzsqppgwqbvkfhjdjd');
},
data: $('form').serialize(),
dataType: "json",
success: function(content) {
// render the JSON result from from the Flex.io pipe
$("#flexio-result-data").text(JSON.stringify(content, null, 2))
var first_item = _.get(content, '[0]', {})
var column_labels = _.map(_.omit(first_item, ['os']), function(val, key) {
if (key != 'os')
return key
})
// use Lodash to reformat the JSON for use with Chart.js
var datasets = _.map(content, function(item) {
// use the 'os' column as our label
var item_label = _.get(item, 'os', 'Not Found')
// create an array of number values from each item's JSON object
var item_values = _.map(_.omit(item, ['os']), function(val) {
return parseFloat(val)
})
return {
label: item_label,
data: item_values,
backgroundColor: getRandomColor()
}
})
var chart_data = {
labels: column_labels,
datasets: datasets
}
// render the JSON result after mapping the data with Lodash
$("#chart-data").text(JSON.stringify(chart_data, null, 2))
// render the chart using Chart.js
var ctx = document.getElementById("canvas").getContext("2d");
window.my_chart = new Chart(ctx, {
type: 'bar',
data: chart_data,
options: {
responsive: true,
legend: {
position: 'top'
},
title: {
display: true,
text: 'Use Flex.io to Create a Chart With Chart.js Directly From a CSV File'
}
}
});
}
});
Feel free to step through the use case and let me know if you have any issues.

The simple example of importing CSV data into ChartJS
index.html:
<!-- ChartJS plugin datasrouce example
chartjs-plugin-datasource: https://nagix.github.io/chartjs-plugin-datasource/
Samples: https://nagix.github.io/chartjs-plugin-datasource/samples/
Specific example: https://nagix.github.io/chartjs-plugin-datasource/samples/csv-index.html
Data source: https://gist.githubusercontent.com/mikbuch/32862308f4f5cac8141ad3ae49e0920c/raw/b2b256d69a52dd202668fe0343ded98371a35b15/sample-index.csv -->
<head>
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.8.0"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datasource#0.1.0"></script>
</head>
<body>
<div>
<canvas id="myChart"></canvas>
</div>
<script src="script.js"></script>
</body>
You can also download this index.html file as a gist.
script.js
// ChartJS plugin datasrouce example
// chartjs-plugin-datasource: https://nagix.github.io/chartjs-plugin-datasource/
// Samples: https://nagix.github.io/chartjs-plugin-datasource/samples/
// Specific example: https://nagix.github.io/chartjs-plugin-datasource/samples/csv-index.html
// Data source: https://gist.githubusercontent.com/mikbuch/32862308f4f5cac8141ad3ae49e0920c/raw/b2b256d69a52dd202668fe0343ded98371a35b15/sample-index.csv
var chartColors = {
red: 'rgb(255, 99, 132)',
blue: 'rgb(54, 162, 235)'
};
var color = Chart.helpers.color;
var config = {
type: 'bar',
data: {
datasets: [{
type: 'line',
yAxisID: 'temperature',
backgroundColor: 'transparent',
borderColor: chartColors.red,
pointBackgroundColor: chartColors.red,
tension: 0,
fill: false
}, {
yAxisID: 'precipitation',
backgroundColor: color(chartColors.blue).alpha(0.5).rgbString(),
borderColor: 'transparent'
}]
},
plugins: [ChartDataSource],
options: {
title: {
display: true,
text: 'CSV data source (index) sample'
},
scales: {
xAxes: [{
scaleLabel: {
display: true,
labelString: 'Month'
}
}],
yAxes: [{
id: 'temperature',
gridLines: {
drawOnChartArea: false
},
scaleLabel: {
display: true,
labelString: 'Temperature (°C)'
}
}, {
id: 'precipitation',
position: 'right',
gridLines: {
drawOnChartArea: false
},
scaleLabel: {
display: true,
labelString: 'Precipitation (mm)'
}
}]
},
plugins: {
datasource: {
type: 'csv',
url: 'https://gist.githubusercontent.com/mikbuch/32862308f4f5cac8141ad3ae49e0920c/raw/b2b256d69a52dd202668fe0343ded98371a35b15/sample-index.csv',
delimiter: ',',
rowMapping: 'index',
datasetLabels: true,
indexLabels: true
}
}
}
};
window.onload = function() {
var ctx = document.getElementById('myChart').getContext('2d');
window.myChart = new Chart(ctx, config);
};
Here is a a gist with this script.js file.
Make sure that both files are in the same directory.
Open index.html with your browser.
Additional materials
CodeSandbox example to preview the example online.
Reason for posting this answer:
I posted this because people are having problems with reading CSV files from the filesystem (directly from the computer) with JavaScript. The examples in chartjs-plugin-datasource documentation don't explain this, and it is assumed that the user has some basic knowledge on the differences in handling URLs from the web, and files from the file system.
My example just shows the basic functionality of the ChartJS datasource plugin, no third-party modules for reading the CSV file are required.
Edit:
According to ggorlen's suggestion from the comment, I also included the code snippets in the answer itself.

Can't post comments on this elitist site, because four years hasn't gotten me enough "points." ....
#huy - interesting how your Codesandbox has completely different code than what you've posted which I found was directly ripped off from another site... it doesn't even relate to the chart you were talking about building. Within Codesandbox, all I see is an image file of the chart, nothing is actually working (and how could it, when the code isn't even related to your dataset!?).

Related

JQgrid - cannot get output from Json where value of array is Object, Object

I have 2 applications that use the free version of jqgrid.
The one that works has a Json array as follows;
Notice the value of data is [...]
For the application where the data does not get rendered;
Notice the value of data is NOT [...]. So what do I need to do to the data to get it in the correct format so that it will render?
EDIT
I think the data issue I raised originally was mistaken.
I have a jsFiddle of what I want and it works, see
https://jsfiddle.net/arame/cxh7zh3a/
But my code in my .Net MVC application does not. The grid is displayed with headers, but the data rows are not rendered.
var populateGrid = function (data) {
var grid = $("#grid");
grid.jqGrid({
data: data,
colNames: ["Contract No", "Title", ""],
colModel: [
{ name: "FullContractNo", label: "FullContractNo", width: 80, align: "center" },
{ name: "ContractTitle", label: "ContractTitle", width: 400, searchoptions: { sopt: ["cn"] } },
{ name: "Link", label: "Link", search: false, align: "center" }
],
cmTemplate: { width: 100, autoResizable: true },
rowNum: 20,
pager: "#pager",
shrinkToFit: false,
rownumbers: true,
sortname: "FullContractNo",
viewrecords: true
});
grid.jqGrid("filterToolbar", {
beforeSearch: function () {
return false; // allow filtering
}
}).jqGrid("gridResize");
$("#divLoading").hide();
}
var getGrid = function () {
var url = GetHiddenField("sir-get-selected-contract-list");
var callback = populateGrid;
dataService.getList(url, callback);
}
getGrid();
The code is a little different to the JsFiddle as the data is extracted from a Web API.
The data is correct however, as I put a breakpoint in and check it.
See
I have found the answer! I feel daft posting this, but for some reason I cannot fathom I had an old version of the jqGrid library. I had version 4.7 and the current version is 4.14.
With the right version it is now working.

EXTJS How to use JSon Reader without proxy

Below is the code where I try to load some records using JSon Reader in the store.
I am unable to see this on the Grid.
Can you please point me out what am I missing as I don't want to use proxy/url for JSon.
var itemsPerPage = 10;
Ext.Loader.setConfig({enabled: true});
Ext.require([
'Ext.grid.*',
'Ext.data.*',
'Ext.util.*',
'Ext.toolbar.Paging'
]);
Ext.define('Assemble', {
extend: 'Ext.data.Model',
fields: [
{name: 'lot_no', type: "string"}
],
idProperty: 'lot_no'
});
Ext.onReady(function() {
Ext.QuickTips.init();
var jsonString = '{"result":[{"lot_no":"MT6261"},{"lot_no":"MT6262"},{"lot_no":"MT6263"}]}';
// create the data store
var store = Ext.create('Ext.data.Store', {
pageSize: itemsPerPage,
proxy:{
type: 'ajax',
reader: {
type: 'json',
root: 'result',
model: Assemble
}
}
});
store.loadData(Ext.decode(jsonString));
console.log(store);
var pagingToolbar = Ext.create('Ext.PagingToolbar',{
pageSize: itemsPerPage,
store: store,
displayInfo: true,
displayMsg: ' {0}-{1},{2}',
emptyMsg: "empty."
});
// create the Grid
var grid = Ext.create('Ext.grid.Panel', {
store: store,
disableSelection: true,
loadMask: true,
columns: [
{
text : 'LOT_NO',
flex : 1,
sortable : true,
dataIndex: 'lot_no'
}
],
bbar : pagingToolbar,
renderTo: 'grid',
viewConfig: {
stripeRows: true,
enableTextSelection: true
}
});
store.loadPage(1);
});
Proxy has to use with url. So, you can't use the proxy like that. I removed the proxy, put the model in store and you have to load objects into store, but in your case contained rootProperty('result', I only get the main objects or you can remove the 'result' from the jsonString). Then, it worked. Chck this fiddle:
https://fiddle.sencha.com/#fiddle/11or
var jsonString = '{"result":[{"lot_no":"MT6261"},{"lot_no":"MT6262"},{"lot_no":"MT6263"}]}';
// create the data store
var store = Ext.create('Ext.data.Store', {
pageSize: itemsPerPage,
model: 'Assemble'
});
store.loadData(Ext.decode(jsonString).result);
Why are you even using a reader? Your data is local so just decode the string and pass in what you want:
https://fiddle.sencha.com/#fiddle/11qc
Also, your data is local so no need for a paging toolbar. In Ext JS 5+ the grid will use the buffered renderer (if the grid has a defined size from height/width configs or from a parent layout) so loading all the data into the store will not affect performance (other than creating the records). The grid will only render what is viewable plus a few on either side.

Highcharts with angularjs drilled down does not work

I am developing a drilled down chart using HichartJS, the chart is getting generated but drill down is not functioning properly.
I need the back button as well so that user can go back to the previous data.
Here is my code,
HTML:
<div ng-controller="myctrl">
<highchart id="chart1" config="highchartsNG"></highchart>
</div>
JS:
var myapp = angular.module('myapp', ["highcharts-ng"]);
myapp.controller('myctrl', function ($scope) {
$scope.highchartsNG = {
options: {
chart: {
type: 'column'
}
},
title: {
text: 'Basic drilldown'
},
xAxis: {
type: 'category'
},
legend: {
enabled: false
},
plotOptions: {
series: {
borderWidth: 0,
dataLabels: {
enabled: true,
}
}
},
series: [{"data":[{"name":"Hiring","y":390309.25,"drilldown":"PRIME MOVER"},{"name":"Private","y":406746.97,"drilldown":"PRIME MOVER"}],"name":"series1","color":"","type":"area"}],
drilldown: {
series: [{"id":"Hiring","data":[["MOTOR CAR",97610],["VAN",129750],["THREE WHEELER",62949.25],["PRIME MOVER",100000]]},{"id":"Private","data":[["MOTOR CAR",488356.97],["VAN",129750],["THREE WHEELER",78949.25],["PRIME MOVER",100000]]}]
}
}
});
Here is the Plunker
Update2 I have made changes for your data , The problem was in formatting of json and the second problem was you were not calling proper id in drillDown. Check the fiddle updated Here with your data
Update1 I have made changes and now its working on fiddle Here . I have added changes to highcharts-ng in script tag in html section of fiddle. Also I changed the data, because your data was not formatted for me.
I just realize that drillDown feature isn't supported by highcharts-ng .see the link Highcharts-ng with drilldown
Following edit was done at source code to make it work.
if(config.drilldown) {
mergedOptions.drilldown = config.drilldown;
};

Plotting Multiple JSON data in flot chart using angularjs

I am using angularjs and JSON to plot flot chart, i am using multiple encoded JSON to draw the line of the Flot line chart, doing so the bar comes out empty.
Not quite sure what is wrong.
HTML
<flot id="placeholder" dataset="dataset" options="options" height="250px"></flot>
JS
.factory("services", ['$http', function($http) {
var serviceBase = 'http://maricoih.e21designs.com/services/'
var obj = {};
obj.getope = function(){
return $http.get(serviceBase + 'productionhourlys');
}
obj.getcopra = function(){
return $http.get(serviceBase + 'productionhourlyscopra');
}
return obj;
}])
.controller('LineChartCtrl', function ($scope,$http,services) {
$scope.dataset = [{
data: obj.getope(),
label: 'OPE',
points: {
show: true,
radius: 6
}
}, {
data: obj.getcopra(),
label: 'OEE',
points: {
show: true,
radius: 6
}
}];
})

JSON + Array events in same calendar?

Good afternoon, currently using JSON feed for my calendar which works ok. Is it possible for me to also add a few events via an array and change colour of these? I want to add bank holidays as an array and colour them green where possible?
Currently my code looks loike this, could I add array of events under the json feed?
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
startParam: 'start',
endParam: 'end',
editable: true,
minTime: 9,
maxTime: 21,
allDayDefault: false,
events : {
url: 'json-events.php',
}
});
Any advice appreciated..
Try this:
In document.ready() method or just before your calendar code. Create event sources like this:
source1 = {
url: 'json-events.php',
type: 'POST',
error: function() {
//alert('There was an error while fetching events!');
},
color: '#4ca64c',
textColor: 'black'
};
source2 = {
url: 'array-events.php',
type: 'POST',
error: function() {
//alert('There was an error while fetching events!');
},
color: '#4caca4',
textColor: 'black'
};
The in fullCalendar declaration:
$('#calendar').fullCalendar({
...
eventSources: [
// your event source
source1,
source2
],
...
});
Hope this helps