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

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.

Related

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
],
]

How to get mapbox-gl-js-offline-example to work?

I'm trying to get self hosted map tiles working with a Mapbox gl js application. As a starting point, I'm trying to get https://github.com/klokantech/mapbox-gl-js-offline-example/blob/gh-pages/index.html to work. I'm open to other ideas like tileserver-gl-light, but I can't get that to work either.
I'm on Windows 10 and have downloaded the .zip from github and changed two lines in index.html to try to get it to work. You can see all of my commented out attempts.
var style = {
"version": 8,
"sources": {
"countries": {
"type": "vector",
// "url": "mapbox://map-id"
// "url": "http://tileserver.com/layer.json",
//"tiles": [location.origin+location.pathname+"countries/{z}/{x}/{y}.pbf"],
//"tiles": ["http://localhost:8080/data/v3/" + "countries/{z}/{x}/{y}.pbf"],
//"tiles": "C:/Users/mattk/Desktop/mapbox-gl-js-offline-example-gh-pages/mapbox-gl-js-offline-example-gh-pages/countries/{z}/{x}/{y}.pbf",
"tiles": "http://localhost:8000/countries/{z}/{x}/{y}.pbf",
"maxzoom": 6
}
},
//"glyphs": location.origin+location.pathname+"font/{fontstack}/{range}.pbf",
//"glyphs": "http://localhost:8080/" + "font/{fontstack}/{range}.pbf",
//"glyphs": "C:/Users/mattk/Desktop/mapbox-gl-js-offline-example-gh-pages/mapbox-gl-js-offline-example-gh-pages/countries/font/{fontstack}/{range}.pbf",
"glyphs": "http://localhost:8000/countries/font/{fontstack}/{range}.pbf",
"layers": [{
"id": "background",
"type": "background",
"paint": {
"background-color": "#ddeeff"
}
When I open up index.html, I can only see the navigational widgets zoom in/out and change bearing to North. Console shows:
Uncaught Error: sources.countries.tiles: array expected, string found
at style_batch.js:45
at Array.forEach (<anonymous>)
at Style.<anonymous> (style_batch.js:43)
but I'm not sure what to do with that
I'm new to GIS, so I'll appreciate it if you explain it to me like I'm 5.

Parsing values from external JSON file with Chart.js

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 .

store the name of a function in a JSON file and later be able to load and call it from within a script?

That title is kind of garbled and this is probably a duplicate but I've been digging a while. This must be really simple. The accepted answer on this question didn't work for me: How to declare and use the name of a function from a json object?
The task: I am trying to externalize the set-up data for a Vis.js timeline into a JSON file . The data set was no problem nor are all of the options except for the function references, "orderByID" and "visTemplate". Those are functions I defined which exist within the script where I am working with the JSON data.
When I try to use the JSON without attempting to convert it, Vis.js complains. When I tried the answer from the question above with the code below, I get the errors show in the image.
This is in Electron and the script is being loaded through a script tag in the index.html.
I await the one-line answer to this simple issue which have spent so much time describing. 😉
console.log(' timelineOptions.order', timelineOptions.order);
console.log(' timelineOptions.template', timelineOptions.template);
console.log('this', this);
console.log('window', window);
timelineOptions.order = window[timelineOptions.orderByID];
timelineOptions.template = window[timelineOptions.visTemplate];
"timelineOptions": {
"order": "orderByID",
"selectable": true,
"zoomable": false,
"width": "100%",
"height": "90%",
"minHeight": 700,
"format": {
"minorLabels": {
"hour": "HH\\h"
}
},
"margin": {
"axis": 20,
"item": 20
},
"start": "2016-12-30",
"end": "2017-01-4",
"template": "visTemplate",
"showCurrentTime": false,
"dataAttributes": "all",
"timeAxis": { "scale": "day", "step": 1 },
"orientation": {
"axis": "top",
"item": "top"
}
}
Not sure if you've setup the right reference on the window object but shouldn't your code read:
timelineOptions.order = window[timelineOptions.order];
You've referenced the string value orderByID instead of the property name you used to set the object up.

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