How to add Dynamics Ticks through JSON in Flot? - javascript

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/

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

Highcharts, build a "Text" graph

I'm using highcharts to build my charts that shows the values that comes from a sensor placed into my garage: all of these values are numeric values, so, i have no problem to build a graph like the following one JSFIDDLE
As i've said, all of the values that comes from the sensor are numeric, except one: the "status", this value is a string value type and it's not a fixed string, it can be:
Transmitting
Standby
Active
Alarm
Or any free string
So, my intention is - and i don't know if that can be feasible - to draw a graph with a fixed serie value (e.g.: 1...maybe i have to use a javascript function that maps the "status" to a given value?) and show that string as fixed datalabels as shown in the fiddle that i've posted.
Final Remarks:
The data that comes from the sensor is a time-series value, like the following:
{"datetime": 1566730095, "status": "transmitting"}
{"datetime": 1566730162, "status": "hello! i'm here"}
This chart will be a separate chart instead the numeric charts, in order to simplify the build and management.
The final goal can be something like that (the following graph is a pure graphical example):
To achieve it you can map data like that:
series: [{
dataLabels: {
enabled: true,
format: '{point.name}',
rotation: -45,
align: 'left',
y: -8
},
data: data.map(item => {
return {
x: item.datetime,
y: 1,
name: item.status
};
})
}]
Demo:
https://jsfiddle.net/BlackLabel/840tv6mz/
To change the way data is exported to CSV you can use this wrapper (edit it as needed):
(function(H) {
H.wrap(H.Chart.prototype, 'getDataRows', function(proceed, multiLevelHeaders) {
var rows = proceed.call(this, multiLevelHeaders);
rows[0][0] = 'Time';
rows[0][1] = 'Status';
rows = rows.map(row => {
if (row.x) {
row[0] = H.dateFormat('%H:%M:%S.%L', row.x);
row[1] = row.name;
}
return row;
});
return rows;
});
}(Highcharts));
Demo:
https://jsfiddle.net/BlackLabel/to92mbu0/

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 .

c3 Charts tooltip doesn't move

I've been trying to get graphing working, all the data seems to be graphing, however the tooltip doesn't move from the far right. This of course is a issue since I cannot then mouse over specific points to see the data.
Here is a JS fiddle example of what's happening: https://jsfiddle.net/kp7eyf8o/6/
NOTE: for some reason the stack overflow JSfiddle gives me an error, but the URL should show my issue.
var chart = c3.generate({
bindto: '#test',
data: {
x: 'x',
columns: [
['x', '2016-01-01', '2016-02-02', '2016-03-03', '2016-04-04', '2016-05-05', '2016-06-06', '2016-07-07', '2016-08-08', '2016-09-09', '2016-10-10', '2016-11-11', '2016-12-12'],
['2016 Actual', 12873666.64, 15976835.94, 19232540.28, 23649495.4, 26338636.36, 29496799.84, 43801703.66, 4263924.64, 5788580.3, ],
['2016 Projected', 3916752.11, 4626643.23, 5146264.25, 6148854.32, 6640724.57, 7409783.48, 8263054.46, 8488001.54, 8837809.1, 9068047.68, 9402019.15, 9513505.72, ],
['2015 Actual', 3256870.0, 3825580.0, 4394290.0, 5550000.0, 6044000.0, 7100000.0, 7700000.0, 8154000.0, 8860000.0, 9200000.0, 9500000.0, 9600328.45, ]
],
colors: {
'2016 Actual': '#2cd554',
'2016 Projected': '#1bc4fc',
'2015 Actual': '#fdaf5a'
}
},
axis: {
x: {
type: 'timeseries',
tick: {
culling: false,
format: '%b'
}
},
y: {
tick: {
format: d3.format("$,.2f")
}
}
},
});
<link href="https://rawgit.com/masayuki0812/c3/master/c3.css" rel="stylesheet" />
<script src="https://rawgit.com/masayuki0812/c3/master/c3.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.3.12/d3.min.js"></script>
<div id="test"></div>
I saw someone mention using 'xs: {x .... y....} but I wasn't able to get that working. I need the X axis to be dates (hard coded right now but in my app I'm using dates associated with one dataset I'm looping through), and the Y axis to be $.
C3 tooltips seem to break when data arrays of different lengths are entered into the columns. You can try putting null values into the shorter array so that the tooltip can move properly.
JS Fiddle: https://jsfiddle.net/stancheta/7zgny2yd/
['2016 Actual', 12873666.64, 15976835.94, 19232540.28, 23649495.4, 26338636.36, 29496799.84, 43801703.66, 4263924.64, 5788580.3, null, null, null],

Highcharts displays series names but missing data points from json source

I am using Highcharts with JSON data to render a standard line chart but am having some trouble getting the series data to display. The chart frame and series names appear on the page and everything checks out in the console, so I know that it has succeeded in fetching the data.
The JSON output appears valid when I run through JSONLint so I'm a little confused as to why this chart will not render correctly.
Here is my chart JAVASCRIPT CODE:
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
type: 'line',
zoomType: "x"
},
xAxis: {
type: 'datetime',
tickInterval: 7 * 24 * 3600 * 1000,
labels: {
format: '{value:%b %e, %Y}',
rotation: -45
},
},
yAxis: {
allowDecimals: true,
title: {
text: '$US'
}
},
tooltip: {
xDateFormat: '%b %e, %Y',
},
series: []
}
$.getJSON("mdb_ajax.php", function(json) {
options.series = new Array();
for(i=0;i< json.length;i++) {
options.series.push(json[i]);
}
var chart = new Highcharts.Chart(options);
});
});
Here's the corresponding PHP FILE:
$price_output = $prices->getPrices($filter_option);
foreach($price_output as $category => $price)
{
$arr[] = array('name' => $category, 'data' => $price);
}
print json_encode($arr);
As you can see I've jury-rigged the object to add "name" and "data" keys to aid Highcharts, but the object results in perfectly valid JSON without this additional work (it just won't display anything this way).
Here is a sample of the JSON DATA:
[
{
"name": "CTGY1",
"data": {
"1414998000000": "6.2400",
"1415084400000": "-3.1110",
"1415170800000": "1.5090",
"1415257200000": "4.2390",
"1415343600000": "1.6990",
"1426140000000": "5.9100"
},
{
"name": "CTGY2",
"data": {
"1414998000000": "7.7890",
"1415084400000": "-0.7610",
"1415170800000": "1.1600",
"1415257200000": "5.3300",
"1415343600000": "1.9290",
"1415602800000": "-0.8260"
}
]
I'm guessing there needs to be some definition of the key-values when processing the fetched JSON data, I'm just not sure what that would look like at this point. Any ideas on the best way to do this?
data should be an array and the Y-values should not be strings in your case:
data: [[1415602800000,-0.8260],[],...]
here are the acceptable data structures for data within series
http://api.highcharts.com/highcharts#series.data
Highcharts API also provide a few examples:
http://jsfiddle.net/gh/get/jquery/1.7.2/highslide-software/highcharts.com/tree/master/samples/highcharts/series/data-array-of-arrays/

Categories

Resources