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/
Related
I am trying to create a highchart based on dynamic data in my Javascript file. I have created a function called dynamicHighchart and it is parsing in JSON 'myJsonString'
The below works fine which is what I got from the console log:
series: [{ "name": "Oct 20", "type": "line", "data": [24025, 24200, 24075, 23925, 23950, 23850, 23650] }, { "name": "Nov 20", "type": "line", "data": [18875, 19125, 18125, 17650, 17500, 16375, 14725, 16625, null, 15550, 14875, 14900, 14925, 15450, 16125, 14500, 13375, 14150, 14150, 12900, 12600, 12950, 13200, 13125, 13175, 13000, 13100, 13100, 13150] }]
but doing this doesn't work - shows as an empty chart:
series: myJsonString
The way I got my stringify JSON is using the following line of code:
myJsonString = JSON.stringify(arr);
Am I parsing myJSON variable in correctly to the series?
My highchart function:
function dynamicHighchart(myJsonString) {
console.log(myJsonString);
var chart = new Highcharts.Chart({
chart: {
renderTo: 'chart1div',
zoomType: 'xy'
},
title: {
text: 'Chart Title'
},
xAxis: {
title: {
enabled: true,
text: 'X axis title'
},
},
yAxis: {
title: {
text: 'Y axis title'
}
},
series: myJsonString
//series: [{ "name": "Oct 20", "type": "line", "data": [24025, 24200, 24075, 23925, 23950, 23850, 23650] }, { "name": "Nov 20", "type": "line", "data": [18875, 19125, 18125, 17650, 17500, 16375, 14725, 16625, null, 15550, 14875, 14900, 14925, 15450, 16125, 14500, 13375, 14150, 14150, 12900, 12600, 12950, 13200, 13125, 13175, 13000, 13100, 13100, 13150] }]
});
}
You need to parse your data from string to an array:
Highcharts.chart('container', {
series: JSON.parse(myJsonString),
...
});
Live demo: http://jsfiddle.net/BlackLabel/c562p8mj/
Chart.js scatter chart only accepts data in a point format (x, y). Im a trying to fill the data points with infomration about medications from a file called meds.json
More specifically, the x would be the month of last fill date of the medication and the y would be the dose.
How can I grab all this data from the meds.json file and insert it to the data to create the points for my scatter plot?
If I try to grab all dates and store them in an array, and all the dose values in another array, how can I use that populate the point data using those arrays?
Here's how to make a scatter plot using Chart.js, I am trying to populate the x,y points under data 'data':
// charts.js
var scatterChart = new Chart(ctx, {
type: 'scatter',
data: {
datasets: [{
label: 'Scatter Dataset',
data: [{
// x = month, y = dose
// fill these in for all meds in the json file
x: -10,
y: 0
}, {
x: 0,
y: 10
}, {
x: 10,
y: 5
}]
}]
},
options: {
scales: {
xAxes: [{
type: 'linear',
position: 'top'
}]
}
}
});
}
meds.json
[
{
"name": "Simvastatin",
"dose": 10,
"dose unit": "mg",
"freq": "qd",
"route": "PO",
"last fill date": "2/15/2020",
"coverage": "100%",
"anticipated remaining fills": 2
},
{
"name": "Lisinopril",
"dose": 5,
"dose unit": "mg",
"freq": "qd",
"route": "PO",
"last fill date": "2/15/2020",
"coverage": "100%",
"anticipated remaining fills": 2
}
...... The list goes on
]
You should actually use a line chart for this which would be much more appropriate and exactly show the trend & relationship between month and the dosage.
But since you asked for scatter chart...you can do it like this :
const data = [{
"name": "Simvastatin",
"dose": 10,
"dose unit": "mg",
"freq": "qd",
"route": "PO",
"last fill date": "2/15/2020",
"coverage": "100%",
"anticipated remaining fills": 2
},
{
"name": "Lisinopril",
"dose": 5,
"dose unit": "mg",
"freq": "qd",
"route": "PO",
"last fill date": "2/15/2020",
"coverage": "100%",
"anticipated remaining fills": 2
}
]
const transformedData = data.map(obj=>{
return {
x:new Date(obj["last fill date"]).getMonth() + 1,
y:obj.dose,
}
})
console.log(transformedData)
and then use as
var scatterChart = new Chart(ctx, {
type: 'scatter',
data: {
datasets: [{
label: 'Scatter Dataset',
data: transformedData
}]
},
options: {
scales: {
xAxes: [{
type: 'linear',
position: 'top'
}]
}
}
});
}
Hope this helps !
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.
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.
Using new Google charts, using the SVG charts, viz 1.1, when running a Stacked bar chart using multiple series, i'm getting a
Chart not displayed due to error: 'Object doesn't support property or method 'contains'' Full error object follows.
then
Using the ng-google-charts wrapper, these are the report options.
$scope.casesChartObject = {
"type": "Bar",
"displayed": true,
"data": data.chartmodel,
"options": {
"title": "...",
"isStacked": "true",
"fill": 20,
"displayExactValues": true,
"vAxis": {
"title": "Infection rate", viewWindowMode: "explicit", viewWindow: { min: 0 }, format: '0.00',
"gridlines": {
"count": 12
}
},
"hAxis": {
"title": "h labal"
},
series:data.series
},
"formatters": {}
};
It works on Chrome and FF, and it's not easy in IE to find the source of the error.
Has anybody had this problem?
TIA