Parsing values from external JSON file with Chart.js - javascript

I have created a simple pie chart using Chart.js. I want to link this to a JSON file on my computer, which is in the same local folder. I then want the data from the JSON file to show up on my pie chart, instead of it being taken directly from the script.
How do I go about doing this? This is my code.
<script>
var ctx = document.getElementById("myDoughnutChart");
var myDoughnutChart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: ["Blue", "Red", "Green", "Orange", "Light Blue"],
datasets: [{
backgroundColor: ["#0074D9", "#FF4136", "#2ECC40", "#FF851B", "#7FDBFF"],
data: [12, 19, 3, 5, 2],
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
showAllTooltips: true,
title: {
display: true,
text: "Responsive test"
},
legend: {
display: false,
fullWidth: true,
labels: {
boxWidth: [50]
},
}
}
});
</script>
This is my JSON file, which is saved under "chart.json" - I am not sure if this is the correct format as I am a real newbie to this.
{"jsonarray": [{
"Color": "Blue",
"Value": 12},
{
"Color": "Red",
"Value": 19},
{
"Color": "Green",
"Value": 3},
{
"Color": "Orange",
"Value": 5},
{
"Color": "Light Blue",
"Value": 2}]
};
I understand a need to parse the JSON file but I have no idea how to do this - thank you so much in advance.

There are a couple parts here.
Step One: load the JSON from a file
I like using Fetch. If you use jQuery, you can also use $.ajax. Assuming the file is in the same directory as your JS code and is named chart.json:
fetch('./chart.json')
.then(function (response) {
return response.json();
}).then(function (json) {
// drawChart fn to be created...see below
drawChart(json);
}).catch(function (error) {
console.error(error);
});
Note that if you are running this code locally, you will probably get an error about CORS if you try to visit the website directly from the filesystem (like file:///<path-to-file>/index.html).
Instead, you can run a local server easily. Go to the directory that contains your file in your terminal, and run:
python -m SimpleHTTPServer 8000
or
php -S localhost:8000
This serves up the current directory on port 8000. Then visit http://localhost:8000/
Also, make sure the JSON is valid (no semicolon at the end!).
Step Two: parse the JSON response
We're trying to make two arrays. One with numbers for data, and one with strings for Labels.
You can do this easily with map:
var graphData = json.jsonarray.map(e => e.Color);
// ["Blue", "Red", "Green", "Orange", "Light Blue"]
var graphLabels = json.jsonarray.map(e => e.Value);
// [12, 19, 3, 5, 2]
Step Three: bring it all together
window.addEventListener("DOMContentLoaded", draw);
function draw() {
// Get the json file with fetch or $.ajax
// Pass the json data to drawChart
}
function drawChart(jsonData) {
/* get graphData and graphLabels
draw chart with your existing code
pass graphData and graphLabels in place of
the hard-coded labels and data in your Chart initialization */
}
extending the idea:
Right now this code only supports a single dataset. The backgroundColor array is fixed, so if you do not have exactly 5 values, some of the background colors will be ChartJS's default gray.
You can further abstract the drawing code to support multiple datasets & even randomly generate colors to match the number of groups if you require it. Just swap out the hard-coded values as needed with variables you generate from your dataset. Hopefully this helps get you started!

The json files are most of the time string type so the chart you want to generate I think it needs a kind of number type so you need to convert your JSON data to a number time
check here,if you do the parsing of JSON correctly check here how its already answered , you'll be ok .

Related

Why prettier put a comma ',' at the last element of the object

In Visual studio code, When I am using chart.js in my app, prettier always put a comma at the end of the last data of the object 'label'. I think, it's create a bug which unable to show my chart on my browser. it show blank. Code is given bellow.
let massPopChart2 = new Chart(myChart2, {
type: "bar", // bar, horizontalBar, pie, line, doughnut, radar, polarArea
data: {
labels: [
"1st Day",
"2nd Day",
"3rd Day",
"4th Day",
"5th Day",
"6th Day",
"7th Day",
],
},
});
can anyone help me figure out why this happening?
JavaScript has allowed trailing commas in array literals since the
beginning, and later added them to object literals (ECMAScript 5) and
most recently (ECMAScript 2017) to function parameters.
This is a relatively new change in syntax, but the basic idea is that by putting a comma on each line allows for:
Easier to add an item or re-order items. Before you always had to check the trailing comma and make sure it was present or removed depending on location.
Removes the need to have one line item be special because it lacks the ,.
Allows for cleaner Git diffs.
You can read up on the full documentation if you like - it goes into further detail:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Trailing_commas
As far as the issue with your chart not displaying, unless you are using a very old browser, a trailing comma should not cause an error/information to not display.
You need to update the configuration of prettier extension.
There are two ways. Below one is mostly used.
Create a .prettierrc file at the root of your project and
specifying the below configuration.
{ "trailingComma": "es5" }
In order to honor the configuration make sure to enable the below
setting in vs code configuration.
"prettier.requireConfig": true
Prettier adds those commas at the end just because if you wanna add another data after that you don't need to type a comma. it does the same for semicolons(;).
you got the error because you haven't provided datasets.
data takes an object which contains labels & datasets values.
{/* <canvas id="myChart" width="400" height="400"></canvas> */}
// var ctx = document.getElementById('myChart');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['1','2'],
datasets: [
{
label: '1st',
data: '120',
borderColor: Utils.CHART_COLORS.red,
backgroundColor: Utils.transparentize(Utils.CHART_COLORS.red, 0.5),
},
{
label: '2',
data: '240',
borderColor: Utils.CHART_COLORS.red,
backgroundColor: Utils.transparentize(Utils.CHART_COLORS.blue, 0.5),
}
]
},
// options: {
// indexAxis: 'y',
// elements: {
// bar: {
// borderWidth: 2,
// }
// },
// responsive: true,
// plugins: {
// legend: {
// position: 'right',
// },
// title: {
// display: true,
// text: 'Chart.js Horizontal Bar Chart'
// }
// }
// },
// };
you can know more about it on official docs https://www.chartjs.org/docs/latest/charts/bar.html

FusionCharts Uncaught Error, Data must be provided in 2D array format or array of json objects

For a project i'm working on with Fusioncharts to render a TimeSeries Chart. The data for the chart is provided by Laravel by passing it through a controller.
Now after a couple of days of debugging, frustration and not being able to figure out the issue i'm here.
I've created a timeseries chart and am trying to render this chart in a div i defined in my blade directive.
I followed this tutorial and read the docs about the specific graph but i end up with the following error:
fusioncharts.js:19 Uncaught Error: Data must be provided in 2D array format or array of json objects
The error itself is pretty clear, the data provided doesnt match the rules that fusioncharts have for delivering the data to the chart. So i started looking at my code and started looking the way i build up my json. The entire proces in creating the json is pretty straight forward and this is the output:
[{"timestamp":"2020-09-25 11:21:24","value":"268.00"},{"timestamp":"2020-09-25 11:21:24","value":"268.00"},{"timestamp":"2020-09-25 11:21:24","value":"268.00"},{"timestamp":"2020-09-25 11:21:25","value":"268.00"},{"timestamp":"2020-09-25 11:21:25","value":"268.00"},{"timestamp":"2020-09-25 11:21:25","value":"268.00"},{"timestamp":"2020-09-25 11:21:25","value":"268.00"},{"timestamp":"2020-09-25 11:21:25","value":"268.00"},{"timestamp":"2020-09-25 11:21:25","value":"268.00"},{"timestamp":"2020-09-25 11:21:25","value":"268.00"},{"timestamp":"2020-09-25 11:21:25","value":"268.00"},{"timestamp":"2020-09-25 11:21:25","value":"268.00"},{"timestamp":"2020-09-25 11:21:25","value":"268.00"}]
In the example fusioncharts provided they use this link to get the data. After looking at both data objects i could find a big difference apart from the key in mine.
This is the code i use to create a chart.
Promise.all([
#json($machine->coldData),
#json($machine->coldDataSchema),
]).then(function(res) {
const data = res[0];
const schema = res[1];
const dataStore = new FusionCharts.DataStore().createDataTable(data, schema);
new FusionCharts({
type: "timeseries",
renderAt: "graph-container",
width: "100%",
height: "400",
dataSource: {
data: dataStore,
chart:{
"theme": "fusion"
},
caption: {
text: "Products on pallet."
},
subcaption: {
text: "Lorem Ipsum...."
},
yaxis: [
{
plot: [
{
value: "Products",
connectnulldata: true
}
],
title: "Products on pallet",
min: "130"
}
]
}
}).render();
});
Its almost the same as the code in the tutorial but i get the error. I also tried the links in the tutorial but get the same error.
Can someone explain why this error occurs and how i should solve it.
Kindly provide the schema in the given format below :
[{
"name": "Time",
"type": "date",
"format": "%Y-%m-%d %H:%M:%S"
}, {
"name": "Products",
"type": "number"
}]
As per the data you have provided, it seems that the data is given in array of objects format and not in 2d array. In order to make your sample work please provide the data in the 2d array format. Below is an example of the same.
[
[
"2020-09-25 11:21:24",
268
],
[
"2020-09-25 11:21:24",
230
],
]

Set custom colour palette in Plotly js in Angular

I am using Plotly js in my recent angular project. I implemented the library successfully by using its angular based wrapper.
There is one thing that I tried to implement in many ways but failed. I am trying to use my custom color palette for its charts.
I find a work around by passing the colour in the chart data layout like,
data = [{
values: allValues[0],
labels: allLabels,
type: 'pie',
name: 'Starry Night',
marker: {
colors: [['rgb(56, 75, 126)', 'rgb(18, 36, 37)', 'rgb(34, 53, 101)', 'rgb(36, 55, 57)', 'rgb(6, 4, 4)']]
},
domain: {
row: 0,
column: 0
},
hoverinfo: 'label+percent+name',
textinfo: 'none'
}
and it worked but it's not the perfect way because I need to add this in every chart data and need to take care of how many data points are there so I push those many color codes.
Is there any way I can provide my color palette in somewhere like config so that every time a chart gets initialize it start taking colors from the custom-defined palette.
The layout property takes a property colorway which takes a list of colour names/codes.
public graph: any = {
data: [],
layout: {
colorway: ["red", "green", "blue", "goldenrod", "magenta"],
autosize: true,
}
}
But I haven't yet figured out how to set this globally.

Problem injecting variable-pie chart with highcharts-export-server

I'm using Highcharts Export Server as a Node.js module to produce charts in PNG format. When I include a Variable Radius Pie Chart though, I get an error in the resulting File. The error is Highcharts error #17:
The requested series type does not exist.
This error happens when you are setting chart.type or series.type to a series type that isn't defined in Highcharts. A typical reason may be that your are missing the extension file where the series type is defined, for example in order to run an arearange series you need to load the highcharts-more.js file.
The chart I'm using is part of the highcharts-more module, so the error makes sense. I even found docs that seemed to spell out my solution. Thre is a resources option where you can provide scripts for injection to your export. That page is here, but I'll include the important bit below:
-resources
{
"files": "highstock.js,highcharts-more.js,data.js,drilldown.js,funnel.js,heatmap.js,treemap.js,highcharts-3d.js,no-data-to-display.js,map.js,solid-gauge.js,broken-axis.js",
"css": "g.highcharts-series path {stroke-width:2;stroke: pink}",
"js": "document.body.style.webkitTransform = \"rotate(-10deg)\";"
}
files: A comma separated string of filenames that need to be injected to the page for rendering a chart. Only files with the extensions .css and .js are injected, the rest is ignored.
css: css inserted in the body of the page
js: javascript inserted in the body of the page
After some digging, I did find that I could pass this resource option as a JSON stringified object into my export parameters. So, I attempted to inject the remote version of highcharts-more.js.
const exportImagesBase64 = async(data, format = 'png') => {
HighchartsExport.initPool();
let resources = JSON.stringify({
files: "http://code.highcharts.com/highcharts-more.js"
});
let charts = data.map(chart => exportPromise({
type: format, //png
options: chart, //standard highcharts config object
resources //resources option to inject highcharts-more
}));
charts = await Promise.all(charts);
HighchartsExport.killPool();
return charts;
};
const exportPromise = (data) => {
return new Promise((resolve, reject) => {
HighchartsExport.export(data, (err, res) => err ? reject(err) : resolve(res));
});
};
Here is an example of what data might be equal to in the code above
[{
"chart": {
"plotBackgroundColor": null,
"plotBorderWidth": null,
"plotShadow": false,
"type": "variablepie",
"height": 300,
"width": 300
},
"title": {
"text": "Placement Breakdown",
"align": "left",
"x": 30,
"y": 30
},
"tooltip": {
"headerFormat": "",
"pointFormat": "<b> {point.name}</b><br/>Impressions: <b>{point.y}</b><br/>Clicks: <b>{point.z}</b><br/>"
},
"plotOptions": {
"pie": {
"allowPointSelect": true,
"cursor": "pointer",
"dataLabels": {
"enabled": false
},
"showInLegend": true
}
},
"series": [
{
"minPointSize": 10,
"innerSize": "20%",
"zMin": 0,
"data": [
{
"name": "facebook",
"y": 13642,
"z": 357
},
{
"name": "instagram",
"y": 12920,
"z": 326
}
]
}
],
"credits": {
"enabled": false
}
}]
Since adding the resource options, I am still receiving the #17 Highcharts error. Am I thinking about this completely wrong? I can't find any more information out there about this, so I'm hoping someone has some knowledge to share.
The documentation for the variable pie chart type refers to highcharts-more.js as a requirement.
The actual requirement for this chart type appears to be modules/variable-pie.js. Using this additional resource instead should fix issues with "The requested series type does not exist" when exporting.

How to add Dynamics Ticks through JSON in Flot?

I want to change the X-Axis values from default to Dynamic Ticks which is passed from JSON.
Through my last post How to plot time values in Flot Graph, I found out that it is possible through Categories.js
I added the JS and modified My JSON in the format below matching to the format given in the Example.
[{"data":[["Over Time",5202]],"label":"Over Time"},{"data":[["Shift Start",19620]],"label":"Shift Start"},{"data":[["Maintenance break",82920]],"label":"Maintenance break"},{"data":[["Lunch break",240]],"label":"Lunch break"},{"data":[["BreakDown",75720]],"label":"BreakDown"},{"data":[["Break",3060]],"label":"Break"},{"data":[["Tea break",72840]],"label":"Tea break"}]
and my JS code as
<script language="javascript" type="text/javascript">
$(document).ready(function(){
$.getJSON('ReasonByTime.txt', function(json) {
$.plot($("#placeholder"),json, {bars: { show: true, barWidth:0.2}, xaxis: { mode: "categories" }});
});
});
When i run this code, x-axis is not displaying any values, the default values also not getting displayed. My result graph is look like this.
I tested The sample example given in code.google.com/p/flot/ but the tickes/categories is not working. I get the Output for the example like this.
Flot is now hosted out of github: https://github.com/flot/flot
If you grab jquery.flot.js and jquery.flot.categories.js from there and run your code, it will work. What does NOT work is jquery.flot.js version 0.7 combined with the latest categories plugin from github.
I ran it with this code and it displayed correctly:
var data = [{
"data": [["Over Time", 5202]]},
{
"data": [["Shift Start", 19620]]},
{
"data": [["Maintenance break", 82920]]},
{
"data": [["Lunch break", 240]]},
{
"data": [["BreakDown", 75720]]},
{
"data": [["Break", 3060]]},
{
"data": [["Tea break", 72840]]}];
$.plot($("#placeholder"), data, {
bars: {
show: true,
barWidth: 0.2
},
xaxis: {
mode: "categories"
}
});​
Here is a working version of it: http://jsfiddle.net/ryleyb/CQ3YS/

Categories

Resources