unix timestamp doesn't work in amcharts for showing chart - javascript

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.

Related

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.

AMCharts Timestamp on x axis

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.

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"
}

AmCharts parseDates unexpected behavior and merges all bars from the chart

I'm using AmCharts to display a chart. It's a floating bar chart displaying sent out surveys to a user. The bars are representing the openFrom to openUntil time, the time window a user has to submit the survey. They're listed in a timeline. I want AmCharts to understand the x-axis has dates as datatype so I can leverage the date functions (relative spacing, showing change of year bold, scrolling in time etc)
The following data is used to plot the chart as seen in the screenshots:
[{
"survey":"Survey DEF",
"openFrom":"05-04-2016",
"openUntil":"04-05-2016",
"status":"Nog niet geopend.", // translates to Not opened yet
"color":"#ededed"
},{
"survey":"Survey DEF",
"openFrom":"01-01-2016",
"openUntil":"31-01-2016",
"status":"Nog niet geopend.",
"color":"#ededed"
},{
"survey":"Survey GHI",
"openFrom":"06-12-2015",
"openUntil":"31-12-2015",
"status":"Ingestuurd op 07-12-2015", // Translates to Submitted at 07-12-2015
"color":"#27ae60"
},{
"survey":"Survey ABC",
"openFrom":"01-12-2015",
"openUntil":"15-12-2015",
"status":"Geopend, nog geen reactie.", // Translates to Opened, not submitted yet
"color":"#e67e22"
},{
"survey":"Survey GHI",
"openFrom":"31-01-2015",
"openUntil":"05-05-2015",
"status":"Geen reactie ontvangen", // Translates to Not submitted
"color":"#c0392b"
}]
Using this code:
var chart = AmCharts.makeChart('chart-container', {
'type': 'serial',
'dataLoader': {
'url': urlToJSONFetchScript
},
'language': 'nl',
'categoryAxis': {
'position': 'right',
'axisAlpha': 0.2,
'gridAlpha': 0.05
},
'valueAxes': [{
'type': 'date',
'minimumDate': '31-01-2015',
'maximumDate': '04-05-2016',
'axisAlpha': 0.2,
'gridAlpha': 0.05
}],
'categoryField': 'survey',
'graphs': [{
'balloonText': '<div style="text-align: left"><strong>[[survey]]</strong><small><br/>[[openFrom]] - [[openUntil]]<br/>[[status]]</small></div>',
'type': 'column',
'dateFormat': 'DD-MM-YYYY',
'openField': 'openFrom',
'valueField': 'openUntil',
'colorField': 'color',
'lineColorField': 'color',
'fillAlphas': 0.65,
'lineAlpha': 0.95
}],
'rotate': true,
'dataDateFormat': 'DD-MM-YYYY'
});
It get's me this chart:
This all looks good, but I'd like to use parseDates zo the x-axis doesn't have string-labels, but relatively spreads the dates and also displaying year changes. When I add 'parseDates': true to categoryAxis the chart rotates and is rendered all wrong. I've been searching in the API documentation for a while but I can't find any solution. What am I missing?
Result with parseDates set to true in categoryAxis options:
If I understand you correctly, the issue is that you need to display all month labels, as well as the year on January.
For this, you will need to set boldPeriodBeginning: true as well as markPeriodChange: true to display year instead of January label.
To make the chart display all months, you'll also need to disable auto grid by setting autoGridCount: false, as well as set gridCount to some larger number, say 25.
Please note that this is all for Value Axis. Enabling parsing of dates for category axis does not make a lot of sense, since you have arbitrary categories,
like "Survey DEF".
'valueAxes': [ {
'type': 'date',
'minimumDate': '31-01-2015',
'maximumDate': '04-05-2016',
'autoGridCount': false,
'gridCount': 25,
'boldPeriodBeginning': true,
'markPeriodChange': true,
'axisAlpha': 0.2,
'gridAlpha': 0.05
} ]
Here's the live chart with the above changes.
As of V3.18 of JavaScript Charts, it is also possible to make the value axis scrollable. To enable that, use valueScrollbar property of the chart. I.e.:
"valueScrollbar": {
"oppositeAxis": false,
"offset": 50,
"scrollbarHeight": 10
}
It's an instance of ChartScrollbar, so you can use any properties available in this class.

Categories