Is it possible to change the animation of line chart on Apexcharts.js from bottom-top to left-right when launching the chart?
I forked this example on Codepen and dug the docs but can't a way to do that.
<div id="chart">
</div>
#chart {
max-width: 650px;
}
var options = {
chart: {
height: 380,
type: "line",
id: "areachart-2"
},
dataLabels: {
enabled: false
},
stroke: {
curve: "straight"
},
series: [
{
data: series.monthDataSeries1.prices
}
],
labels: series.monthDataSeries1.dates,
xaxis: {
type: "datetime",
labels: {
rotate: 0,
formatter: function(val) {
return dayjs(val).format('MMM YYYY')
}
},
tooltip: {
formatter: function(val) {
return dayjs(val).format('MMM YYYY')
}
}
},
tooltip: {
x: {
formatter: function(val) {
return dayjs(val).format('MMM DD, YYYY');
}
}
}
};
var chart = new ApexCharts(document.querySelector("#chart"), options);
chart.render();
var totalIncident = [151, 169, 311, 614, 840];
var ransomDemands = [18, 60, 150, 383, 555];
var forensicsCosts = [24, 33, 58, 109, 103];
var xCat = ['2017', '2018', '2019', '2020', '2021'];
var defaultValues = new Array(totalIncident.length).fill(null);
var totalIncidentD = [...defaultValues]
var ransomDemandsD = [...defaultValues]
var forensicsCostsD = [...defaultValues]
var options = {
series: [{
name: "Total Incident Costs",
data: defaultValues
}, {
name: "Ransom Demands",
data: defaultValues
}, {
name: "Forensics Costs",
data: defaultValues
}],
colors: ['#A0CEE8', '#4060AC', '#EC6058'],
chart: {
height: 500,
width: 1200,
type: 'line',
zoom: {
enabled: false
},
fontFamily: 'Raleway, sans-serif',
animations: {
speed: 13000,
easing: 'linear',
dynamicAnimation: {
speed: 1000
}
}
},
dataLabels: {
enabled: true,
formatter: function (val, opt) {
if (val === null) return;
return val + "K"
},
},
stroke: {
curve: 'straight'
},
title: {
text: 'Ransomware',
align: 'center'
},
grid: {
row: {
colors: ['#f3f3f3', 'transparent'],
opacity: 0.5
},
},
xaxis: {
type: 'category',
tickPlacement: 'between',
categories: xCat,
},
yaxis: {
min: 0,
max: 1000,
labels: {
formatter: function (value) {
return value + "K";
}
},
}
};
var chart = new ApexCharts(document.querySelector("#chart"), options);
chart.render();
var i = 0;
var dataInterval = setInterval(function () {
totalIncidentD[i] = totalIncident[i];
ransomDemandsD[i] = ransomDemands[i];
forensicsCostsD[i] = forensicsCosts[i];
chart.updateSeries([{
name: "Total Incident Costs",
data: totalIncidentD
}, {
name: "Ransom Demands",
data: ransomDemandsD
}, {
name: "Forensics Costs",
data: forensicsCostsD
}])
i = i + 1;
if (i === xCat.length) clearInterval(dataInterval)
}, 1000)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.apexcharts-canvas {
margin: auto;
}
</style>
</head>
<body>
<div id="chart"></div>
</body>
<script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
</html>
Related
I am trying to set the values of bars in descending order. First way is to make a key value pair like passing company name along with value and then sort them. But the issue is I am sending an array of 10 companies as label and then array of 10 companies as data. I dont know how to send them as object of array and sort it. or is there any other way to do it in chart js. A
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css"
integrity="sha512-1ycn6IcaQQ40/MKBW2W4Rhis/DbILU74C1vSrLJxCq57o941Ym01SwNsOMqvEBFlcgUa6xLiPY/NS5R+E6ztJQ=="
crossorigin="anonymous" referrerpolicy="no-referrer" />
<link href='https://fonts.googleapis.com/css?family=Hind' rel='stylesheet'>
<title>Sarmaaya Charts</title>
</head>
<style>
body {
color: rgb(177, 177, 177) !important;
}
</style>
<body>
<div class="container m-3 ">
<div class="row ">
<div class="col-lg-12 col-md-12 col-sm-12 bg-white">
<h6 class=" ">Top Points Contributor </h6>
<hr width="100%">
<canvas id="topContributor"></canvas>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-datalabels/2.0.0/chartjs-plugin-datalabels.min.js"
integrity="sha512-R/QOHLpV1Ggq22vfDAWYOaMd5RopHrJNMxi8/lJu8Oihwi4Ho4BRFeiMiCefn9rasajKjnx9/fTQ/xkWnkDACg=="
crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
Chart.register(ChartDataLabels);
function createChart(topGainersNames, topGainersChange, topLosersNames, topLosersChange) {
return {
labels: chartLabels,
datasets: [
{
type: 'bar',
label: topGainersNames,
//label: ['FFC', 'CCF', 'DFG', 'FFC', 'MTL', 'SYS', 'INDU', 'ACLU', 'ABC', 'XYZ', 'EFl', 'LMK'],
data: topGainersChange,
backgroundColor: '#2FC798',
borderColor: '#2FC798',
datalabels: {
align: 'top',
anchor: 'end',
offset: 4,
color: '#2FC798',
},
},
{
type: 'bar',
label: topLosersNames,
data: topLosersChange,
backgroundColor: '#C72151',
borderColor: '#C72151',
datalabels: {
align: 'bottom',
anchor: 'end',
offset: 4,
color: '#C72151',
},
},
],
}
}
function chartStyling() {
return {
animation: {
duration: 500,
},
responsive: true,
interaction: {
mode: 'index',
intersect: false
},
layout: {
padding: 20
},
elements: {
point: {
hoverRadius: 6
}
},
plugins: {
tooltip: {
caretSize: 10,
yAlign: 'bottom',
caretPadding: 50,
padding: 10,
position: 'nearest',
mode: 'nearest',
intersect: false,
enabled: true,
borderWidth: 20,
intersect: true,
backgroundColor: 'rgb(92, 89, 89)',
callbacks: {
/*label: function (context) {
//console.log('aa', context.dataset.data[context.dataIndex])
//return context.dataset.label[context.dataIndex] + '\n' +
// context.dataset.data[context.dataIndex];
//return `${context.dataset.label[context.dataIndex]} \n Index Point : 15.45 \n Weight :0.68% \n Market Cap : Rs. 12,79,90,000 \n % Px Chg : 5.55% \n`
return `(${context.dataset.label[context.dataIndex]} + "/n" + 'rs').split('\n')`;
},*/
label: function (context) {
return context.dataset.label[context.dataIndex];
},
afterLabel: function (context) {
var someValue2 = "\nIndex Point: \nWeight: \nMarket Cap: \n% Px Chg: ";
return someValue2;
}
}
},
elements: {
point: {
pointStyle: 'rect'
}
},
legend: {
display: false,
position: 'top',
align: 'end',
labels: {
boxWidth: 5,
usePointStyle: true,
}
},
datalabels: {
display: true,
borderWidth: 0.5,
color: 'black',
formatter: function (value, context) {
//console.log(context.dataset.label)
return context.dataset.label[context.dataIndex] + '\n' + 'Rs ' + value
},
font: {
size: 10,
weight: 'bold',
}
}
},
scales: {
y: {
display: false,
stacked: true,
grid: {
display: false,
lineWidth: 3
},
},
x: {
stacked: true,
display: false,
grid: {
display: false,
},
}
}
}
}
chartLabels = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
var formdata = new FormData();
formdata.append("market_symbol", "KSE100");
var sam;
var requestOptions = {
method: 'POST',
body: formdata,
redirect: 'follow',
};
var topGainers = [18.32, 12.37, 11.37, 10.22, 9.45, 8.98, 8.76, 7.34, 6.4, 5.21, 4.32, 3.22]
var topLosers = [-8.32, -7.37, -6.37, -5.39, -5.37, -4.37, -4.19, -3.77, -3.12, -2.98, -2.34, -2.19]
fetch("https://dev-api.sarmaaya.pk/3.0/view_market_performers.php", requestOptions)
.then(response => response.json())
.then(data => apiData(data)
).catch(error =>
console.log('error', error)
);
const apiData = (data) => {
var topGainersNames = []
var topLosersNames = []
var topGainersChange = []
var topLosersChange = []
for (var i = 0; i < data.gainers.length; i++) {
topGainersNames.push(data.gainers[i].stock_symbol)
topLosersNames.push(data.losers[i].stock_symbol)
topGainersChange.push(data.gainers[i].stock_change)
topLosersChange.push(data.losers[i].stock_change)
}
console.log('topGainersNames', topGainersNames)
console.log('topGainersChange', topGainersChange)
console.log('topLosersNames', topLosersNames)
console.log('topLosersChange', topLosersChange)
var ctx = document.getElementById('topContributor').getContext('2d');
var myChart = new Chart(ctx, {
data: createChart(topGainersNames, topGainersChange, topLosersNames, topLosersChange),
options: chartStyling()
})
}
</script>
</body>
</html>
I'm trying to render a line chart, with category names shown in the tooltip.
I got the following line chart:
let dataCurrent = [
{'x': 'FIRST', 'y': 711}, {'x': 'SECOND', 'y': 709}, {'x': 'THIRD', 'y': 522}
]
let options = {
chart: {
type: "line",
fontFamily: 'inherit',
height: 150.0,
sparkline: {
enabled: true
},
animations: {
enabled: true
},
},
tooltip: {
enabled: true,
onDatasetHover: {
highlightDataSeries: true,
},
x: {
show: true,
formatter: function (value) {
console.log(value) // This value should be "FIRST", "SECOND" and "THIRD", but it's 1, 2 and 3
return value;
},
},
y: {
formatter: function (val) {
return Math.floor(val)
}
}
},
dataLabels: {
enable: true,
position: 'bottom'
},
fill: {
opacity: 1,
},
stroke: {
width: [2, 1],
dashArray: [0, 3],
lineCap: "round",
curve: "smooth",
},
series: [{
name: dataCurrentName,
data: dataCurrent
},
grid: {
strokeDashArray: 4,
},
xaxis: {
labels: {
formatter: function (value) {
console.log(value) // This shows the correct category name
return value;
},
},
tooltip: {
enabled: false,
},
type: "category",
},
yaxis: {
labels: {
padding: 4
},
},
colors: [primaryColor, secondaryColor],
legend: {
show: false,
position: 'top',
offsetY: -3
},
};
let chart = new ApexCharts(document.querySelector("#line-chart"), options);
chart.render();
For some reason, the tooltip of the x axis doesn't show the value of x in dataCurrent. It shows sequential numbers (1, 2, 3), no matter what the category name is.
If I log the value of x in xaxis instead, it shows the correct value. What am I doing wrong?
Currently, you only parsed the value to the tooltip formatter. Please refer to the documentation for the available variables to parse in this formatter. You can find a working example below where the categoryLabel is shown in the tooltip.
Please note that you had some syntax errors in your code as well. I commented them in the working example below.
If you would like to see all the available variables to parse in to the formatter, you can use the function below instead:
formatter: function (value, { series, seriesIndex, dataPointIndex, w }) {
console.log(
"value:", value + '\n' +
"series:", series + '\n' +
"seriesIndex:", seriesIndex + '\n' +
"dataPointIndex:", dataPointIndex + '\n' +
"w:", w
);
console.log(w.globals.categoryLabels[value - 1]);
return w.globals.categoryLabels[value - 1]
},
//https://apexcharts.com/docs/options/tooltip/
let dataCurrent = [
{
'x': 'FIRST',
'y': 711
},
{
'x': 'SECOND',
'y': 709
},
{
'x': 'THIRD',
'y': 522
},
]
let options = {
chart: {
type: "line",
fontFamily: 'inherit',
height: 150.0,
sparkline: {
enabled: true
},
animations: {
enabled: true
},
},
tooltip: {
enabled: true,
onDatasetHover: {
highlightDataSeries: true,
},
x: {
show: true,
formatter: function (value, { w }) {
// Please refer to documentation, available options are: value, series, seriesIndex, dataPointIndex, w, categoryLabels
console.log(w.globals.categoryLabels[value - 1]);
return w.globals.categoryLabels[value - 1]
},
},
y: {
formatter: function (val) {
return Math.floor(val)
}
}
},
dataLabels: {
enable: true,
position: 'bottom'
},
fill: {
opacity: 1,
},
stroke: {
width: [2, 1],
dashArray: [0, 3],
lineCap: "round",
curve: "smooth",
},
series: [{
// name: dataCurrentName, // ---> ReferenceError: dataCurrentName is not defined
data: dataCurrent
}],
grid: {
strokeDashArray: 4,
},
xaxis: {
labels: {
formatter: function (value) {
console.log(value) // This shows the correct category name
return value;
},
},
tooltip: {
enabled: false,
},
type: "category",
},
yaxis: {
labels: {
padding: 4
},
},
// colors: [primaryColor, secondaryColor], // ---> ReferenceError: primaryColor is not defined
legend: {
show: false,
position: 'top',
offsetY: -3
},
};
let chart = new ApexCharts(document.querySelector("#line-chart"), options);
chart.render();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- <link rel="stylesheet" href="style.css"> -->
<title>Test</title>
</head>
<body>
<div id="line-chart"></div>
</body>
<script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
</html>
I have the following code to generate a pie chart. I am calling an external json file to generate the pie chart.
For some reason. it not generating the pie chart. what am i missing or doing wrong?
Here is my code below:
<div id="container" style="min-width: 310px; height: 400px; max-width: 600px; margin: 0 auto"></div>
JAVASCRIPT
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.5/js/bootstrap.min.js"></script>
<!-- high chart libarary -->
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/highcharts-3d.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script>
var options = {
chart: {
renderTo: 'container',
type: 'pie',
options3d: {
enabled: true,
alpha: 15,
beta: 15,
depth: 50,
viewDistance: 25
}
},
title: {
text: '',
},
subtitle: {
text: '',
},
xAxis: {
categories: []
},
yAxis: {
enabled: false,
title: {
text: 'Amount'
},
labels: {
// formatter:function() {
// return Highcharts.numberFormat(this.value, 0, '', ',');
// }
// ,enabled: false
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return '<b>' + this.series.name + '</b><br/>' +
this.x + ': $' + Highcharts.numberFormat(this.y, 0, '', ',');
}
},
credits: {
enabled: false
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
depth: 35,
dataLabels: {
enabled: true,
format: '{point.name}'
}
}
},
legend: {
enabled: false
},
series: [{}]
}
setTimeout(function() {
$.getJSON("pie.json", function(json) {
// options.xAxis.categories = json[0]['data'];
// options.series[0] = json[1];
// options.series[1] = json[2];
// chart = new Highcharts.Chart(options);
// debugger
console.log(json);
alert(json);
options.series[0].data = json
chart = new Highcharts.Chart(options);
});
}, 0)
</script>
JSON - pie.json
[{
name: 'Microsoft Internet Explorer',
y: 56.33
}, {
name: 'Chrome',
y: 24.03,
sliced: true,
selected: true
}, {
name: 'Firefox',
y: 10.38
}, {
name: 'Safari',
y: 4.77
}, {
name: 'Opera',
y: 0.91
}, {
name: 'Proprietary or Undetectable',
y: 0.2
}]
Here we are.The pie json data need a transfrom as I show you below:
var options = {
chart: {
renderTo: 'container',
type: 'pie',
options3d: {
enabled: true,
alpha: 15,
beta: 15,
depth: 50,
viewDistance: 25
}
},
title: {
text: '',
},
subtitle: {
text: '',
},
xAxis: {
categories: []
},
yAxis: {
enabled: false,
title: {
text: 'Amount'
},
labels: {
// formatter:function() {
// return Highcharts.numberFormat(this.value, 0, '', ',');
// }
// ,enabled: false
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return '<b>' + this.series.name + '</b><br/>' +
this.x + ': $' + Highcharts.numberFormat(this.y, 0, '', ',');
}
},
credits: {
enabled: false
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
depth: 35,
dataLabels: {
enabled: true,
format: '{point.name}'
}
}
},
legend: {
enabled: false
},
series: [{type:"pie"}]
}
setTimeout(function() {
$.getJSON("pie.json", function(json) {
console.log(json);
alert(json);
options.series[0].data = json;
chart = new Highcharts.Chart(options);
});
}, 0);
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.5/js/bootstrap.min.js"></script>
<!-- high chart libarary -->
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/highcharts-3d.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
</head>
<body>
<div id="container" style="min-width: 310px; height: 400px; max-width: 600px; margin: 0 auto"></div>
</body></html>
pie..json
[{
"name": "Microsoft Internet Explorer",
"y": 56.33
}, {
"name": "Chrome",
"y": 24.03,
"sliced": true,
"selected": true
}, {
"name":"Firefox",
"y": 10.38
}, {
"name":"Safari",
"y": 4.77
}, {
"name":"Opera",
"y": 0.91
}, {
"name": "Proprietary or Undetectable",
"y": 0.2
}]
Highcharts drilldown is not working . Scenario is From graph, if i click any point It needs to show another graph using avgTimes.testIds (check below json). But i am unable to get testId value when i click on the point.
Please check Json and Javascript for reference .
"this.series.data.indexOf( this.point )" code is not working to get the indexValue, it is giving "undefined" as response.Please check javascript code
Response json Json:
{
"testid": {
"name": "testId",
"data": [
208,
207,
206,
205,
202
]
},
"xaxis": {
"xaxis": "xaxis",
"data": [
"2016/03/21 01:50:04",
"2016/03/20 04:56:20",
"2016/03/20 04:41:56",
"2016/03/18 11:09:53",
"2016/03/18 09:33:15"
]
},
"avgTimes": {
"name": "avgTime",
"units": "ms",
"data": [
1894,
3141,
44966,
1792,
22929
],
"testIds": [
208,
207,
206,
205,
202
]
}
}
Below is the javascript which i am using
var options;
var chart;
$(document).ready(function() {
init();
});
function init() {
$('#back_btn').hide();
options = {
chart: {
renderTo: 'container',
type: 'line',
zoomType: 'x',
},
title: {
text: ''
},
subtitle: {
text: ''
},
xAxis: {
categories: [],
labels: {
align: 'center',
x: -3,
y: 20,
formatter: function() {
return Highcharts.dateFormat('%b-%d', Date.parse(this.value));
}
}
},
yAxis: {
title: {
text: ''
}
},
tooltip: {
enabled: true,
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
'<b>'+ this.x +': '+ this.y+' '+'</b><br/>'+
'TestId: '+this.series.options.testIds[this.series.data.indexOf(this.point)];
}
},
plotOptions: {
line: {
cursor: 'pointer',
point: {
events: {
click: function() {
//document.write(this.series.options.testIds[this.series.data.indexOf( this.point )]);
$('#dateDisplay').text(this.series.options.testIds[this.series.data.indexOf( this.point )]);
$.getJSON("http://localhost:8080/reports/graph/transaction?testId="+this.series.options.testIds[this.series.data.indexOf( this.point )], function(json){
options.xAxis.categories = json.xAxis.xaxisList;
options.series[0] = json.avgTimes;
options.series[1] = json.tps;
options.series[2] = json.minTimes;
options.series[3] = json.maxTimes;
options.xAxis.labels = {
formatter: function() {
//return Highcharts.dateFormat('%l%p', Date.parse(this.value +' UTC'));
return Highcharts.dateFormat('%l%p', Date.parse(this.value));
//return this.value;
}
}
options = new Highcharts.Chart(options);
$('#back_btn').show();
});
}
}
},
dataLabels: {
enabled: true
}
}
},
series: [{
type: 'line',
name: '',
data: []
}]
}
$.getJSON("http://localhost:8080/reports/graph/tests?limit=10&offset=1&env=stg&project=MarketplaceOffers&userCount=10", function(json){
options.xAxis.categories = json.xaxis.data;
options.series[0]= json.avgTimes;
//options.series[1]=json.testid;
//options.series[1].extra= json.testid;
chart = new Highcharts.Chart(options);
});
}
function goback() {
init();
$('#dateDisplay').text("2013-02");
}
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Dynamic Drill Down in Highcharts</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.1/themes/base/jquery-ui.css" />
<style>
body,h1,h2,h3,h4,h5,h6,p,ul,ol,dl,input,textarea { font-family: 'Lucida Grande', Tahoma, Verdana, sans-serif; }
</style>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.1/jquery-ui.js"></script>
<script src="date.js"></script>
<script src="dynamicChats.js"></script>
</head>
<body>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<strong><div id="dateDisplay">2013-02</div></strong>
<div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div>
Back
</body>
</html>
this.point is undefined that's why you can't retrieve the index from this.series.data array. It seems that when a point is clicked on the graph, this refers to the point object itself in the click handler.
You should replace the line bellow :
this.series.options.testIds[this.series.data.indexOf(this.point)]
by this one :
this.series.options.testIds[this.series.data.indexOf(this)]
I also moved the creation of the object options inside the getJSON callback function :
<script>
var chart;
$(document).ready(function () {
init();
});
function init() {
$('#back_btn').hide();
$.getJSON("http://localhost:8080/reports/graph/tests?limit=10&offset=1&env=stg&project=MarketplaceOffers&userCount=10", function (json) {
var options = {
chart: {
renderTo: 'container',
type: 'line',
zoomType: 'x',
},
title: {
text: ''
},
subtitle: {
text: ''
},
xAxis: {
categories: [],
labels: {
align: 'center',
x: -3,
y: 20,
formatter: function () {
return Highcharts.dateFormat('%b-%d', Date.parse(this.value));
}
}
},
yAxis: {
title: {
text: ''
}
},
tooltip: {
enabled: true,
formatter: function () {
return '<b>' + this.series.name + '</b><br/>' +
'<b>' + this.x + ': ' + this.y + ' ' + '</b><br/>' +
'TestId: ' + this.series.options.testIds[this.series.data.indexOf(this.point)];
}
},
plotOptions: {
line: {
cursor: 'pointer',
point: {
events: {
click: function () {
//document.write(this.series.options.testIds[this.series.data.indexOf( this.point )]);
$('#dateDisplay').text(this.series.options.testIds[this.series.data.indexOf(this.point)]);
$.getJSON("http://localhost:8080/reports/graph/transaction?testId=" + this.series.options.testIds[this.series.data.indexOf(this)], function (json) {
options.xAxis.categories = json.xAxis.xaxisList;
options.series[0] = json.avgTimes;
options.series[1] = json.tps;
options.series[2] = json.minTimes;
options.series[3] = json.maxTimes;
options.xAxis.labels = {
formatter: function () {
//return Highcharts.dateFormat('%l%p', Date.parse(this.value +' UTC'));
return Highcharts.dateFormat('%l%p', Date.parse(this.value));
//return this.value;
}
}
options = new Highcharts.Chart(options);
$('#back_btn').show();
});
}
}
},
dataLabels: {
enabled: true
}
}
},
series: [{
type: 'line',
name: '',
data: []
}]
};
options.xAxis.categories = json.xaxis.data;
options.series[0] = json.avgTimes;
chart = new Highcharts.Chart(options);
});
}
function goback() {
init();
$('#dateDisplay').text("2013-02");
}
</script>
Highcharts - Multiple pie charts from json
Let's say I have a server with 4 hard drives. How do I show 4 pie charts, one for each hard drive? It works if the chart type is stacked column (code below).
JSON produces this output:
[{
"name":"Drive",
"data":["C:","D:","E:","F:"]},{
"name":"Free",
"data":[673869,2267920,105627,307096]},{
"name":"Used",
"data":[94029,2264810,6373,104]
}]
And my script code (for stacked column):
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Stacked column chart with data from MySQL using Highcharts</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var options = {
colors: ['#50B432', '#ED561B'],
chart: {
renderTo: 'container',
type: 'column',
marginRight: 130,
marginBottom: 25
},
title: {
text: 'Server',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
categories: []
},
yAxis: {
title: {
text: 'Used / Free'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
this.x +' '+ Highcharts.numberFormat(this.percentage, 2) +' %';
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
plotOptions: {
column: {
stacking: 'normal',
dataLabels: {
enabled: true,
color: '#000000',
formatter: function() {
return bytes(this.point.y, true);
}
}
}
},
series: []
}
$.getJSON("data2.php", function(json) {
options.xAxis.categories = json[0]['data'];
options.series[0] = json[1];
options.series[1] = json[2];
chart = new Highcharts.Chart(options);
});
});
function bytes(bytes, label) {
if (bytes == 0) return '';
var s = ['MB', 'GB', 'TB', 'PB'];
var e = Math.floor(Math.log(bytes)/Math.log(1024));
var value = ((bytes/Math.pow(1024, Math.floor(e))).toFixed(2));
e = (e<0) ? (-e) : e;
if (label) value += ' ' + s[e];
return value;
}
</script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
</head>
<body>
<div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div>
</body>
</html>
Thank you for any suggestions.
You can iterate on each json item and create new div (by for example append) and init chart.
What is important, all values in data should be numbers, not strings like you have.
Example:
http://jsfiddle.net/9ov3en2t/
$(function () {
var json = [{
"name": "Drive",
"data": ["C:", "D:", "E:", "F:"]
}, {
"name": "Free",
"data": [673869, 2267920, 105627, 307096]
}, {
"name": "Used",
"data": [94029, 2264810, 6373, 104]
}];
var each = Highcharts.each,
$charts = $('#charts');
each(json,function(item, i) {
$charts.append('<div id="container' + i + '"></div>');
var $chart = $('#container' + i);
$chart.highcharts({
chart:{
type:'pie'
},
series:[{
name: item.name,
data: item.data
}]
});
});
});