AMCharts Timestamp on x axis - javascript

have some problem with AMCharts library.
With Java have build a service which return datas in JSON format like this:
[{"datum":"2017-11-05 14:30:00","temperatura":17.2754,"slanost":38.0844},
{"datum":"2017-11-05 14:00:00","temperatura":17.1836,"slanost":38.1}]
What I want is to have datetime on x axis and temperature or / and salinity on y axis..
my html code is like this:
var chart = AmCharts.makeChart( "chartdiv", {
"type": "serial",
"dataLoader": {
"url": "rest/podatki/tempslajson"
},
"categoryField": "datum",
"dataDateFormat": "YYYY-MM-DD JJ:NN:SS",
"startDuration": 1,
"rotate": false,
"categoryAxis": {
"parseDates": true,
"minPeriod": "ss"
},
"graphs": [ {
"valueField": "temperatura",
"bullet": "round",
"bulletBorderColor": "#FFFFFF",
"bulletBorderThickness": 2,
"lineThickness ": 2,
"lineAlpha": 0.5
}]
} );
The problem is that I'm not shure if the dataDateFormat is right?!
the result I get is like this (but is wrong)
what I'am doing wrong?!

Date-based data must be in ascending order in AmCharts, as noted in the parseDates documentation. Per the docs:
Important: If this is set to true, the data points needs to come pre-ordered in ascending order. Data with incorrect order might result in visual and functional glitches on the chart.
Your sample data is in descending order, which is likely causing your issue.

Related

unix timestamp doesn't work in amcharts for showing chart

I'm using a unix timestamp as a category field of my chart but it doesn't work. Here is a sample of my json data:
{
"id": 1546387200,
"upload_id": 1,
"bg": 23
}
The id is a unix timestamp and I'm using this field as a category field of my chart:
"categoryField": "id",
"categoryAxis": {
"dashLength": 1,
"minorGridEnabled": true,
"labelsEnabled": true,
"tickLength": 0
},
Why isn't this working?
First of all I recommend switching to amcharts4, because it is much more flexible and has even new chart types. You can migrate easily, beginning with just one chart. You can use amcharts3 and amcharts4 in parallel (Migration Guide).
To solve your problem you should set the parseDates property for your categoryAxis and set it to true (docs).
"categoryAxis": {
"dashLength": 1,
"minorGridEnabled": true,
"labelsEnabled": true,
"tickLength": 0,
"parseDates": true
},
I created this code pen as reference. Hope that helps.

amcharts adding legand with the dynamic text

I am using amcharts for rendering the data in column charts, I need the legand to be shown along with the text of the each 'valueField'.
I am trying something like this :
"legend": {"horizontalGap": 10,
"maxColumns": 1,
"position": "right",
"useGraphSettings": true,
"markerSize": 10,
"marginTop": 10,
"labelText":"[[value]]"
}
My JSFiddle
It's showing the different colors well, but the text is not getting displayed.
Any suggestions would be highly appreciable!
You need to set the title of the graphs so that the legend knows what to use to replace the labelText of each legend, which defaults to [[title]]:
https://docs.amcharts.com/3/javascriptcharts/AmLegend#labelText
It looks like the labelText will not parse any other special placeholders like [[value]] other than [[title]].
So the fix is, just to remove what you have set as the label text in the legend section (just leave it as default), and add titles on each graph:
legend: {
...,
// "labelText": "[[value]]"
},
...,
graphs: [
{
id: "g1",
fillAlphas: .9,
title: "value 1",
...
},
{
id: "g2",
fillAlphas: .9,
title: "OR WHATEVER YOU WANT TO DISPLAY",
...
},
...
]
fiddle: https://jsfiddle.net/davidliang2008/fm7jLkta/

Getting the weather forecast data to load in amcharts dataloader

I am very new to programming. So please bear with me.
I want to show the real time weather forecast data, specifically the temperature and precipitation vs time period using amcharts.
The weather data I am taking from openweathermap.org. Sample: "https://samples.openweathermap.org/data/2.5/forecast?q=M%C3%BCnchen,DE&appid=b6907d289e10d714a6e88b30761fae22"
And I want it to use in the following standard amcharts example with dataloader.
var chart = AmCharts.makeChart("chartdiv", {
"type": "serial",
"theme": "dark",
"dataLoader": {
"url": "data/serial2.json",
"showErrors": true,
"complete": function ( chart ) {
console.log( "Loading complete" );
},
"load": function ( options, chart ) {
console.log( "File loaded: ", options.url );
},
"error": function ( options, chart ) {
console.log( "Error occured loading file: ", options.url );
}
},
"categoryField": "year",
"startDuration": 1,
"rotate": false,
"categoryAxis": {
"gridPosition": "start"
},
"valueAxes": [{
"position": "top",
"title": "Million USD",
"minorGridEnabled": true
}],
"graphs": [{
"type": "column",
"title": "Income",
"valueField": "income",
"fillAlphas":1,
"balloonText": "<span style='font-size:13px;'>[[title]] in [[category]]:<b>[[value]]</b></span>"
}, {
"type": "line",
"title": "Expenses",
"valueField": "expenses",
"lineThickness": 2,
"bullet": "round",
"balloonText": "<span style='font-size:13px;'>[[title]] in [[category]]:<b>[[value]]</b></span>"
}],
"legend": {
"useGraphSettings": true
},
"creditsPosition": "top-right",
"responsive": {
"enabled": true
}
});
function reloadData() {
chart.dataLoader.loadData();
}
The problem I am facing is that the weather data is a complex json and I am not being able to simply replace the catagory field and value field with the temperature and precipitation.
Can anyone guide me how to go about this? Any lead will be much aprreciated.
Thank you!
Given that your source JSON is in a complex format that doesn't directly work with AmCharts, you have to use the dataLoader's postProcess callback to take the response and adapt it to your needs. If you look at the openweathermap sample API response documentation, you'll see that it maps out each field and what they correspond to. The main properties of interest are: main.temp, dt, rain.3h and snow.3h. You'll want to pull this information out for each point and assign it to your array. Your API response has each point under the list array, so you'll want to loop through that.
Here's what the postProcess method will look like:
"dataLoader": {
"url": "YOUR API URL HERE",
"postProcess": function(jsonData) {
var newData = []; //dataProvider for your chart
//loop through your API response's list array for the data you need
jsonData.list.forEach(function(periodInfo) {
//set up the data point with the converted timestamp,
//converted temperature, and placeholder for precipitation
var dataPoint = {
"date": periodInfo.dt * 1000, //convert to milliseconds
"temperature": periodInfo.main.temp - 273.15, //convert kelvin to celsius
"precipitation": 0
};
//check if we have a value for rain precipitation before adding it to our precipitation property
if (periodInfo.rain !== undefined && periodInfo.rain['3h'] !== undefined) {
dataPoint.precipitation += periodInfo.rain['3h'];
}
//check if we have a value for snow precipitation before adding it in
if (periodInfo.snow !== undefined && periodInfo.snow['3h'] !== undefined) {
dataPoint.precipitation += periodInfo.snow['3h'];
}
//finally, add it to your new data array
newData.push(dataPoint);
});
//return the new array to be assigned to the chart's dataProvider
return newData;
}
},
Now you have your data mapped, you have to update your makeChart call to look for those properties by creating graph objects with the corresponding valueField properties (temperature and precipitation), setting your categoryField to date and create a categoryAxis with parseDates enabled and a minPeriod set to hh since the data is hourly. You might also want to create a second value axis for your precipitation values.
Here's a snippet of the updated makeChart properties:
//create value axes for both temperature and precip values
"valueAxes": [{
"id": "temperature",
"title": "Temperature (C)"
}, {
"id": "precipitation",
"title": "Precipitation (mm)",
"position": "right"
}],
"synchronizeGrid": true, //make sure the grids from both axes are synchronized
"graphs": [{
"bullet": "round",
"valueField": "temperature"
},{
"fillAlphas": 0.9,
"lineAlpha": 0.2,
"type": "column",
"valueField": "precipitation",
"valueAxis": "precipitation" //plot this against the precipitation value axis
}],
"categoryField": "date",
"categoryAxis": {
"parseDates": true,
"minPeriod": "hh" //make sure we plot hourly data correctly
},
Here's a demo using a static JSON file of the above API response to illustrate this. I added some other quality of life settings such as a cursor and setting the precision. I recommend looking at the AmCharts API documentation for more information.

AmChart multiples date values

I'm trying to create a chart with multiples date values but it's not working. I thing that the logic is good and that amChart doesn't like this date format. Any ideas ?
The working exemple :
var chart = AmCharts.makeChart( "chartdiv", {
type: "xy",
dataProvider: [ {
"ax": 16.10, <--------
"ay": 2,
"bx": 16.11, <--------
"by": 2
}, {
"ax": 16.20, <--------
"ay": 3,
"bx": 16.21, <--------
"by": 3
}],
graphs: [ {
"xField": "ax",
"yField": "ay"
}, {
"xField": "bx",
"yField": "by"
} ],
} );
What I'm trying to get :
var chart = AmCharts.makeChart( "chartdiv", {
type: "xy",
dataProvider: [ {
"ax": "2017/04/27 09:16:10", <--------
"ay": 2,
"bx": "2017/04/27 09:16:11", <--------
"by": 2
}, {
"ax": "2017/04/27 09:16:20", <--------
"ay": 3,
"bx": "2017/04/27 09:16:21", <--------
"by": 3
}],
graphs: [ {
"xField": "ax",
"yField": "ay"
}, {
"xField": "bx",
"yField": "by"
} ],
} );
http://jsfiddle.net/Lktv4s4b/1/
For date-based data, you have to specify a dataDateFormat for your chart object so that AmCharts knows how to correctly parse your date. Since you're using an XY chart, you also have to tell AmCharts that you have a date-based value axis (XY charts only have value axes, unlike Serial charts) and you have to specify which one is date-based. Going by your data, your X axis is date-based, so you need to at least tell it that the bottom value axis' type is "date":
AmCharts.makeChart("chartdiv", {
type: "xy",
dataDateFormat: "YYYY/MM/DD JJ:NN:SS",
valueAxes: [{
position: "bottom",
type: "date"
}], //you can also specify the second value axis' properties if needed, but it will create a numeric y-axis for you by default if you don't
// ... rest of your properties omitted ...
});
Updated fiddle: http://jsfiddle.net/Lktv4s4b/2/

Flot graph shifting upwards when trying to hide the second axis ticks

I am currently working on some flot graphs that display single and multiple sets of data relating to time. Below is an example image of a single set of data on the graph.
Single data set
A date time picker allows a user to compare two time ranges where the second data set draws over the initial set. The issue I'm having is that when the second dataset is drawn over the first the whole graph shifts upwards revealing a large white space where the hidden ticks should be, see the example image below.
Multiple dataset
As you can see the data sets are different time ranges therefore can't be on the same axis as they are a comparison. Here's my options for the axes.
xaxes: [{
tickColor: "#fff",
mode: "time",
timeformat: timeFormat,
minTickSize: tickSize,
font: {
style: "normal",
color: "#666666"
},
axisLabel: xLabel,
axisLabelUseCanvas: true,
axisLabelFontSizePixels: 11,
axisLabelColour: "#666666",
axisLabelFontFamily: 'Open Sans',
axisLabelPadding: 20
},
{
ticks: [],
mode: "time",
timeFormat: timeFormat
}],
applying the option show: false on the second xaxis removes the shifting completely however because it is false my tooltips for the graph points are also removed.
I m using flot.time, flot.tooltip and flot.axislabels if needed to know.
This is my first question so any feedback would be great :)
My example on JSFiddle.
It all comes down to 2 main changes. Assign your compare graph data to second x-axis:
var dataSet = [{
data: [
[1467669600000, 12],
[1467709200000, 14]
],
label: 'data1',
xaxis: 1
}, {
data: [
[1467583200000, 15],
[1467622800000, 13],
[1467662400000, 16]
],
label: 'data2',
xaxis: 2
}];
For aesthetics, you should hide the second x-axis, so it won't mirror the same hours (set show: false)
{
"show": false,
"mode": "time",
"timeformat": "%H:%M",
"tickSize": [2, "hour"],
"min": 1467583200000,
"max": 1467666000000,
"timezone": "browser"
}

Categories