I am using AmCharts for displaying chart data. I am using different data sets for different zoom levels. Like for 1D, I use Minutes data; For 1W, I use Hours data and for 1Y I use Days data. I change the datasets by calculating difference in minutes for startDate and endDate for generated "changed" event of PeriodSelector.
The problenm is that when I am currently at 1D zoom level, and I click Max, the difference in minutes is equal to 2 days and it displays only 2 days data as I have only that much in the minutes dataset. I want it to display the Days dataset which I have for 2 years. But the event generated has min startDate and max endDate only for current dataset which has just 2 days data.
The predefinedPeriod property in the changed event contains the label of the button that was clicked. You can use that to detect which button was clicked:
listeners: [
{
event: "changed",
method: function(eventObj) {
console.log("clicked " + eventObj.predefinedPeriod);
}
}
]
Demo:
var chartData1 = [];
generateChartData();
var chart = AmCharts.makeChart("chartdiv", {
type: "stock",
theme: "light",
dataSets: [
{
fieldMappings: [
{
fromField: "value",
toField: "value"
},
{
fromField: "volume",
toField: "volume"
}
],
dataProvider: chartData1,
categoryField: "date"
}
],
panels: [
{
showCategoryAxis: false,
stockGraphs: [
{
id: "g1",
valueField: "value",
comparable: true,
compareField: "value",
balloonText: "[[title]]:<b>[[value]]</b>",
compareGraphBalloonText: "[[title]]:<b>[[value]]</b>"
}
]
}
],
periodSelector: {
position: "left",
periods: [
{
period: "MM",
selected: true,
count: 1,
label: "1 month"
},
{
period: "YYYY",
count: 1,
label: "1 year"
},
{
period: "YTD",
label: "YTD"
},
{
period: "MAX",
label: "MAX"
}
],
listeners: [
{
event: "changed",
method: function(eventObj) {
console.log("clicked " + eventObj.predefinedPeriod);
}
}
]
}
});
function generateChartData() {
var firstDate = new Date();
firstDate.setDate(firstDate.getDate() - 500);
firstDate.setHours(0, 0, 0, 0);
for (var i = 0; i < 500; i++) {
var newDate = new Date(firstDate);
newDate.setDate(newDate.getDate() + i);
var a1 = Math.round(Math.random() * (40 + i)) + 100 + i;
var b1 = Math.round(Math.random() * (1000 + i)) + 500 + i * 2;
chartData1.push({
date: newDate,
value: a1,
volume: b1
});
}
}
html, body {
width: 100%;
height: 100%;
margin: 0px;
}
#chartdiv {
width: 100%;
height: 100%;
}
<script src="//www.amcharts.com/lib/3/amcharts.js"></script>
<script src="//www.amcharts.com/lib/3/serial.js"></script>
<script src="//www.amcharts.com/lib/3/themes/light.js"></script>
<script src="//www.amcharts.com/lib/3/amstock.js"></script>
<div id="chartdiv"></div>
Related
Does anyone know of a chart layout that functions like a schedule/timeline?
I currently have a chart that shows the on/off status of 3 valves over time.
It's a stacked line/area chart, it's works ok, but it's not the easiest to follow.
See linked screenshot of what I'm looking to achieve: Chart actual vs desired (Top is current chart, bottom is what I want to achieve).
Is this possible with apache echarts?
Thanks to #pthomson for pointing me in the right direction.
Here is what I've come up with: Codepen chart example
I'm still having some issues with the min/max values for the xAxis.
The min/max seems to be calculated on values in index 1, which is the end timestamp of each schedule piece, so not ideal.
var dom = document.getElementById('chart-container');
var myChart = echarts.init(dom, null, {
renderer: 'canvas',
useDirtyRect: false
});
var app = {};
var option;
const valveColors = [
"#f59527",
"#00e200",
"#2da8f3",
]
var data = [
{
"name": "Valve 1",
"value": [
1655647200000,
1657980000000,
0
]
},
{
"name": "Valve 3",
"value": [
1657980000000,
1659448800000,
2
]
},
{
"name": "Valve 1",
"value": [
1659448800000,
1660526144467,
0
]
},
{
"name": "Valve 2",
"value": [
1655647200000,
1660526144467,
1
]
}
];
option = {
xAxis: {
type: "time",
//Min is getting values from index 1, not sure why
min: range => range.min - (7 * 24 * 60 * 60 * 1000), //Subtract 7 days
},
yAxis: {
type: "category",
data: [ "Valve 3", "Valve 2", "Valve 1" ]
},
series: [
{
type: "custom",
renderItem: (params, api) => {
var catIndex = api.value(2);
var timeSpan = [api.value(0), api.value(1)];
var start = api.coord([timeSpan[0], 2 - catIndex]);
var end = api.coord([timeSpan[1], 2 -catIndex]);
var size = api.size([0,1]);
var height = size[1] * 0.6;
var rect = echarts.graphic.clipRectByRect(
{ x: start[0], y: start[1] - height / 2, width: end[0] - start[0], height: height},
{ x: params.coordSys.x, y: params.coordSys.y, width: params.coordSys.width, height: params.coordSys.height}
);
return (
rect && {
type: "rect",
transition: ["shape"],
shape: rect,
style: {
fill: valveColors[catIndex],
},
}
);
},
encode: {
x: [0,1],
y: 0,
},
data: data,
}
],
tooltip: {
show: true,
trigger: "item",
formatter: params => {
return `${params.data.name}<br/> ${params.data.value[0]} - ${params.data.value[1]}` //Unix timestamps should be converted to readable dates
}
},
dataZoom: [
{
type: "slider",
filterMode: "none"
},
],
}
if (option && typeof option === 'object') {
myChart.setOption(option);
}
window.addEventListener('resize', myChart.resize);
I use highmaps with "Rich information on click" in a json format. For this I used a previously existing example. However, there are a few parts that I would like to add.
Separate container in which the extra information (countryChart) is
displayed instead of a single container in which both the map and
the extra information are shown Solution given by ppotaczek
Is it possible to display the total per category if no country is selected. In the example below, this means that in (Countrychart)
graph, cat1: 14, cat2: 3 and cat3: 15 (Canada, US and India added
together) are shown. Solution given by ppotaczek
The flags are not displayed, I cannot figure out why this is. Solution given by Emad
In this example I have made a start on the graph hopefully this is a good basis for the extra functionality.
$.ajax({
url: 'https://cdn.rawgit.com/highcharts/highcharts/v6.0.4/samples/data/world-population-history.csv',
success: function() {
var jsondata = {
"data": [{
"value": "8",
"code": "in",
"name": "india",
"testdata": [{
"vcount": "3"
}, {
"vcount": null
}, {
"vcount": "5"
}]
}, {
"value": "15",
"code": "us",
"name": "united states",
"testdata": [{
"vcount": "9"
}, {
"vcount": "2"
}, {
"vcount": "4"
}]
}, {
"value": "9",
"code": "ca",
"name": "canada",
"testdata": [{
"vcount": "2"
}, {
"vcount": "1"
}, {
"vcount": "6"
}]
}]
}
var mapChart;
var countryChart;
var graphdata = [];
var graphdataf = [];
var valuecount;
var countries = {};
$.each(jsondata.data, function(i, item) {
var graphval = [];
var value = item.value;
var code = item.code;
var name = item.name;
graphval.push(code);
graphval.push(value);
graphdata.push(graphval);
$.each(item.testdata, function(j, itemval) {});
countries[item.code] = {
name: item.name,
code3: item.code,
data: item.testdata
};
});
var data = [];
for (var code3 in countries) {
if (countries.hasOwnProperty(code3)) {
$.each(countries[code3].data, function(j, itemval) {
//var graphvaldata = [];
var value = itemval.vcount;
data.push({
name: countries[code3].name,
code3: code3,
value: value,
});
});
}
}
// Wrap point.select to get to the total selected points
Highcharts.wrap(Highcharts.Point.prototype, 'select', function(proceed) {
proceed.apply(this, Array.prototype.slice.call(arguments, 1));
var points = mapChart.getSelectedPoints();
if (points.length) {
if (points.length === 1) {
$('#info #flag').attr('class', 'flag ' + points[0].flag);
$('#info h2').html(points[0].name);
} else {
$('#info #flag').attr('class', 'flag');
$('#info h2').html('Comparing countries');
}
$('#info .subheader').html('<h4>Historical population</h4><small><em>Shift + Click on map to compare countries</em></small>');
if (!countryChart) {
countryChart = Highcharts.chart('country-chart', {
chart: {
height: 250,
spacingLeft: 0
},
credits: {
enabled: false
},
title: {
text: null
},
subtitle: {
text: null
},
xAxis: {
tickPixelInterval: 50,
crosshair: true,
categories: ['cat1', 'cat2', 'cat3']
},
yAxis: {
title: null,
opposite: true
},
tooltip: {
split: true
},
plotOptions: {
series: {
animation: {
duration: 500
},
marker: {
enabled: false
}
}
}
});
}
$.each(points, function(i, point) {
var data,
dataRaw = countries[point['hc-key']].data;
if (dataRaw) {
data = dataRaw.map((p) => parseInt(p.vcount));
}
// Update
if (countryChart.series[i]) {
countryChart.series[i].update({
name: this.name,
data: data,
type: points.length > 1 ? 'column' : 'column'
}, false);
} else {
countryChart.addSeries({
name: this.name,
data: data,
type: points.length > 1 ? 'column' : 'column'
}, false);
}
});
while (countryChart.series.length > points.length) {
countryChart.series[countryChart.series.length - 1].remove(false);
}
countryChart.redraw();
} else {
$('#info #flag').attr('class', '');
$('#info h2').html('');
$('#info .subheader').html('');
if (countryChart) {
countryChart = countryChart.destroy();
}
}
});
// Initiate the map chart
mapChart = Highcharts.mapChart('container', {
title: {
text: 'Population history by country'
},
subtitle: {
text: 'Source: The World Bank'
},
mapNavigation: {
enabled: true,
buttonOptions: {
verticalAlign: 'bottom'
}
},
colorAxis: {
type: 'logarithmic',
endOnTick: false,
startOnTick: false,
minColor: '#fff',
maxColor: '#3D1C5C',
min: 5,
max: 15,
},
tooltip: {
footerFormat: '<span style="font-size: 10px">(Click for details)</span>'
},
credits: {
enabled: false
},
series: [{
data: graphdata,
mapData: Highcharts.maps['custom/world'],
joinBy: 'hc-key',
name: 'Total Play',
allowPointSelect: true,
cursor: 'pointer',
states: {
select: {
color: '#a4edba',
borderColor: 'black',
dashStyle: 'shortdot'
}
}
}]
});
}
});
* {
font-family: sans-serif;
}
#wrapper {
height: 500px;
width: 1000px;
margin: 0 auto;
padding: 0;
overflow: visible;
}
#container {
float: left;
height: 500px;
width: 700px;
margin: 0;
}
#info {
float: left;
width: 270px;
padding-left: 20px;
margin: 100px 0 0 0;
border-left: 1px solid silver;
}
#info h2 {
display: inline;
font-size: 13pt;
}
#info .f32 .flag {
vertical-align: bottom !important;
}
#info h4 {
margin: 1em 0 0 0;
}
#media screen and (max-width: 920px) {
#wrapper,
#container,
#info {
float: none;
width: 100%;
height: auto;
margin: 0.5em 0;
padding: 0;
border: none;
}
}
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/maps/modules/map.js"></script>
<script src="https://code.highcharts.com/mapdata/custom/world.js"></script>
<!-- Flag sprites service provided by Martijn Lafeber, https://github.com/lafeber/world-flags-sprite/blob/master/LICENSE -->
<link rel="stylesheet" type="text/css" href="//github.com/downloads/lafeber/world-flags-sprite/flags32.css" />
<div id="wrapper">
<div id="container"></div>
<div id="info">
<span class="f32"><span id="flag"></span></span>
<h2></h2>
<div class="subheader">Click countries to view history</div>
<div id="country-chart"></div>
</div>
</div>
Thanks in advance for your help!
I can aswer to your third question : The flags are not displayed, I cannot figure out why this is.
The problem is with this line :
$('#info #flag').attr('class', 'flag ' + points[0].flag);
There is no flag property in points object, you can change it to this :
$('#info #flag').attr('class', 'flag ' + points[0]["hc-key"]);
And you will have the flag now.
https://jsfiddle.net/vq26m8nb/7/
As to your questions:
Both charts are already in separate containers. You can remove the div with 'wrapper' id to split them so that they do not appear side by side. Check this example: https://jsfiddle.net/BlackLabel/8jo7vzty/
Yes, for example you can call select on some point with an additional argument and sum the data in the wrapped select method (depending on that additional argument).
if (points.length) {
...
if (arguments[3]) {
totalData = [];
Highcharts.objectEach(countries, function(el){
el.data.forEach(function(val, i){
if (totalData[i]) {
totalData[i] += parseInt(val.vcount)
} else {
totalData[i] = parseInt(val.vcount);
}
});
});
$('#info h2').html('Total data');
countryChart.series[0].setData(totalData);
mapChart.series[0].points[0].select(false, false, true);
}
} else if (!arguments[3]) {
$('#info #flag').attr('class', '');
$('#info h2').html('');
$('#info .subheader').html('');
if (countryChart) {
countryChart = countryChart.destroy();
}
}
...
mapChart = Highcharts.mapChart('container', ...);
mapChart.series[0].points[0].select(true, false, true);
Live demo: https://jsfiddle.net/BlackLabel/mg7x3kje/
The flags are not displayed because your points do not have flag property. You can add them in the way as #Emad Dehnavi suggested.
Is it possible to rolloverSlice a pie chart based on seconds without an event?
Is clicking or hovering the part of the chart is the only way to rollover a slice or is there anyway to forloop this by index to show the parts every seconds
Here is my code
<script src="http://www.amcharts.com/lib/3/amcharts.js"></script>
<script src="http://www.amcharts.com/lib/3/pie.js"></script>
<script src="http://www.amcharts.com/lib/3/themes/light.js"></script>
<div id="asset--chart"></div>
<style>
#asset--chart {
width : 100%;
height : 500px;
font-size : 11px;
}
</style>
var pieChartData = [
{
asset: 'Funiture',
marketValue: 50000.00
}, {
asset: 'Cash',
marketValue: 6250.00
}, {
asset: 'Car',
marketValue: 10000.00
}, {
asset: 'Other',
marketValue: 11250.00
}
];
chartAsset = AmCharts.makeChart(
'asset--chart', {
type: 'pie',
dataProvider: pieChartData,
valueField: 'marketValue',
titleField: 'asset',
startEffect: 'easeOutSine',
pulledField: 'pullOut',
//pullOutOnlyOne: true,
// pullOutEffect: 'easeInSine',
responsive: {
enabled: true
},
labelsEnabled: false,
balloon: {
fillAlpha: 0.95,
borderThickness: 1,
borderColor: '#000000',
shadowAlpha: 0,
}
}
);
chartAsset.addListener('rollOverSlice', function(e) {
chartAsset.clickSlice(e.dataItem.index);
});
Here is the fiddle: http://jsfiddle.net/Lrktmwa5/
AmCharts provides manual rollOverSlice and rollOutSlice methods that take the index of the slice where you want to simulate hover and mouseout actions. You can call them in a setInterval or setTimeOut loop depending on your use case:
var counter = 0;
setInterval(function() {
//check if the previous slice is pulled out in order
//to simulate a mouseout action to pull it back in for this chart
if (chartAsset.chartData[(counter + (chartAsset.dataProvider.length - 1)) % chartAsset.dataProvider.length].pulled) {
chartAsset.rollOutSlice((counter + (chartAsset.dataProvider.length - 1)) % chartAsset.dataProvider.length);
}
chartAsset.rollOverSlice(counter);
counter = (counter + 1) % chartAsset.dataProvider.length;
}, 5000);
Demo below:
var pieChartData = [{
asset: 'Funiture',
marketValue: 50000.00
}, {
asset: 'Cash',
marketValue: 6250.00
}, {
asset: 'Car',
marketValue: 10000.00
}, {
asset: 'Other',
marketValue: 11250.00
}];
chartAsset = AmCharts.makeChart(
'asset--chart', {
type: 'pie',
dataProvider: pieChartData,
valueField: 'marketValue',
titleField: 'asset',
startEffect: 'easeOutSine',
pulledField: 'pullOut',
//pullOutOnlyOne: true,
// pullOutEffect: 'easeInSine',
responsive: {
enabled: true
},
labelsEnabled: false,
balloon: {
fillAlpha: 0.95,
borderThickness: 1,
borderColor: '#000000',
shadowAlpha: 0,
}
}
);
chartAsset.addListener('rollOverSlice', function(e) {
chartAsset.clickSlice(e.dataItem.index);
});
chartAsset.addListener('rollOutSlice', function(e) {
chartAsset.clickSlice(e.dataItem.index);
});
var counter = 0;
setInterval(function() {
//check if the previous slice is pulled out in order
//to simulate a mouseout action to pull it back in for this chart
if (chartAsset.chartData[(counter + (chartAsset.dataProvider.length - 1)) % chartAsset.dataProvider.length].pulled) {
chartAsset.rollOutSlice((counter + (chartAsset.dataProvider.length - 1)) % chartAsset.dataProvider.length);
}
chartAsset.rollOverSlice(counter);
counter = (counter + 1) % chartAsset.dataProvider.length;
}, 5000);
body, html {
width: 100%;
height: 100%;
margin: 0;
}
#asset--chart {
width: 100%;
height: 100%;
font-size: 11px;
}
<script src="http://www.amcharts.com/lib/3/amcharts.js"></script>
<script src="http://www.amcharts.com/lib/3/pie.js"></script>
<script src="http://www.amcharts.com/lib/3/themes/light.js"></script>
<div id="asset--chart"></div>
i added this code
scales:
{
xAxes:
[{
type: 'time',
time:
{
unit: 'month',
displayFormats: { month: 'MM' },
max: '2017-10-09 18:43:53',
min: '2017-10-02 18:43:53'
}
}]
},
to the options but it does not work. Any ideas what i'm making wrong?
FIDDLE ->
https://jsfiddle.net/o473y9pw/
Since you wish to use time for x-axis, your labels array should be an array of date/time string (labels array is correspondent to x-axis).
You would also need to set the parser property (to parse the date/time correctly), and x-axis' ticks source to data (to properly generate x-axis ticks).
UPDATE
If you only have a min and max date then, you can create a nice little plugin to populate the labels (date) array dynamically, as such :
plugins: [{
beforeInit: function(chart) {
var time = chart.options.scales.xAxes[0].time, // 'time' object reference
// difference (in days) between min and max date
timeDiff = moment(time.max).diff(moment(time.min), 'd');
// populate 'labels' array
// (create a date string for each date between min and max, inclusive)
for (i = 0; i <= timeDiff; i++) {
var _label = moment(time.min).add(i, 'd').format('YYYY-MM-DD HH:mm:ss');
chart.data.labels.push(_label);
}
}
}]
note: moment.js is used to make calculations easier.
ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ ⧩
( for demonstration purposes, I've changed the time unit to day )
$(document).ready(function() {
new Chart(document.getElementById("chartBox"), {
type: 'line',
data: {
datasets: [{
data: [12, 19, 3, 5, 2, 3, 32, 15],
label: "",
borderWidth: 2,
borderColor: "#3e95cd",
fill: false,
pointRadius: 0
}]
},
options: {
scales: {
xAxes: [{
type: 'time',
time: {
parser: 'YYYY-MM-DD HH:mm:ss',
unit: 'day',
displayFormats: {
day: 'ddd'
},
min: '2017-10-02 18:43:53',
max: '2017-10-09 18:43:53'
},
ticks: {
source: 'data'
}
}]
},
legend: {
display: false
},
animation: {
duration: 0,
},
hover: {
animationDuration: 0,
},
responsiveAnimationDuration: 0
},
plugins: [{
beforeInit: function(chart) {
var time = chart.options.scales.xAxes[0].time, // 'time' object reference
timeDiff = moment(time.max).diff(moment(time.min), 'd'); // difference (in days) between min and max date
// populate 'labels' array
// (create a date string for each date between min and max, inclusive)
for (i = 0; i <= timeDiff; i++) {
var _label = moment(time.min).add(i, 'd').format('YYYY-MM-DD HH:mm:ss');
chart.data.labels.push(_label);
}
}
}]
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/moment#latest/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.0/Chart.min.js"></script>
<canvas id="chartBox"></canvas>
The dataset should be an array of objects with properties x for time and y for value.
$(document).ready(function() {
var data = [{
x: new moment().add(-10, "months"),
y: Math.random() * 100
},
{
x: new moment().add(-8, "months"),
y: Math.random() * 100
},
{
x: new moment().add(-6, "months"),
y: Math.random() * 100
},
{
x: new moment().add(-4, "months"),
y: Math.random() * 100
},
{
x: new moment().add(-2, "months"),
y: Math.random() * 100
},
{
x: new moment().add(-0, "months"),
y: Math.random() * 100
},
];
new Chart(document.getElementById("chartBox"), {
type: 'line',
data: {
datasets: [{
data: data,
borderColor: "#3e95cd",
fill: false
}]
},
options: {
scales: {
xAxes: [{
type: 'time'
}]
},
legend: false
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.0/Chart.bundle.min.js"></script>
<canvas id="chartBox"></canvas>
Fiddle
If the xAxis label is in date format use this code
time:
{
format: 'MM',
unit: 'month',
displayFormats: { month: 'MM' },
max: '2017-10-09 18:43:53',
min: '2017-10-02 18:43:53'
}
If the xAxis label is as what u used numerals use
time:
{
format: 'MM',
unit: 'month',
parser:'MM',
displayFormats: { month: 'MM' },
max: '2017-10-09 18:43:53',
min: '2017-00-02 18:43:53'
}
You might want to change a few things.
Your data should include time data.
If you set scale unit to be month, your min max should be more than one month to see the actual scales.
Here's simplified working example.
https://jsfiddle.net/f2xmkkao/
I'm trying to add a listener to amCharts' stockChart but can't find where.
According to the docs of chartCursor you can set changed event on chartCursor however chartCursor does not exist on stockChart, only regular charts according to the docs of the StockChart.
As far as I can see the only semi-relevant settings is chartCursorSettings but it does not allow setting any listeners.
How can I catch mouse move/changed event over amCharts' amStockChart ?
The changed event can be caught at the panel level:
var chart = AmCharts.makeChart("chartdiv", {
// ...
"panels": [{
// ...
"listeners": [{
"event": "changed",
"method": function(e) {
console.log('changed event fired')
}
}],
}],
// ...
});
Demo below:
var chart = AmCharts.makeChart("chartdiv", {
"type": "stock",
"theme": "light",
"categoryAxesSettings": {
"minPeriod": "mm"
},
"dataSets": [{
"fieldMappings": [{
"fromField": "value",
"toField": "value"
}],
"dataProvider": generateChartData(),
"categoryField": "date"
}],
"panels": [{
"stockGraphs": [{
"valueField": "value",
"type": "smoothedLine"
}],
"listeners": [{
"event": "changed",
"method": function(e) {
console.log('changed event fired')
}
}],
}],
"chartCursorSettings": {
"valueBalloonsEnabled": true
}
});
function generateChartData() {
var chartData = [];
var firstDate = new Date( 2012, 0, 1 );
firstDate.setDate( firstDate.getDate() - 1000 );
firstDate.setHours( 0, 0, 0, 0 );
for ( var i = 0; i < 1000; i++ ) {
var newDate = new Date( firstDate );
newDate.setHours( 0, i, 0, 0 );
var a = Math.round( Math.random() * ( 40 + i ) ) + 100 + i;
chartData.push( {
date: newDate,
value: a
} );
}
return chartData;
}
#chartdiv {
width: 100%;
height: 300px;
}
<script src="//www.amcharts.com/lib/3/amcharts.js"></script>
<script src="//www.amcharts.com/lib/3/serial.js"></script>
<script src="//www.amcharts.com/lib/3/themes/light.js"></script>
<script src="//www.amcharts.com/lib/3/amstock.js"></script>
<div id="chartdiv"></div>