Really new to Vue , can you help me with a sum? - javascript

thanks for anybody reading me here ,
I have got this code from my prof and I want ,need to calculate automatically the sum , the total of the players in the html I mean being displayed.
I'm really new to this , can anybody help me out ?
Want to understand The Vue.js math functions in order to progress in my studies and in math as well.
Last..so full of doubt here , sorry guys , Vue.js is a js library ..so I cannot put a js script inside vue.js right ?
Thanks
var players = [
{ label: 'A', value: 100 },
{ label: 'B', value: 100 },
{ label: 'C', value: 100 },
{ label: 'D', value: 100 },
{ label: 'E', value: 100 },
{ label: 'F', value: 100 }
]
Vue.component("polygraph", {
template: "#polygraphComponent",
props: ["stats", "width"],
computed: {
radius() { return (this.width / 2); },
viewbox() {
var size = this.width;
var min = -(size / 2);
return [min, min, size, size].join(" ");
},
points() {
var total = this.stats.length
return this.stats.map((stat, i) => {
var point = valueToPoint(stat.value, i, total)
return point.x + "," + point.y
}).join(" ")
}
},
components: {
axisLabel: {
template: "#axisLabelComponent",
props: {
stat: Object,
index: Number,
total: Number
},
computed: {
point() {
return valueToPoint(
this.stat.value,
this.index,
this.total
)
}
}
}
}
})
new Vue({
el: "#app",
data: {
newLabel: "",
players: players,
width: 600
},
methods: {
add(evt) {
evt.preventDefault()
if (!this.newLabel) return
this.players.push({
label: this.newLabel,
value: 100
})
this.newLabel = ""
},
remove(stat) {
if (this.players.length > 3) {
this.players.$remove(stat)
} else {
alert("Can't remove more!")
}
}
},
components: {
scoreControl: {
template: "#scoreControlComponent",
props: {
stat: Object,
index: Number,
total: Number
},
computed: {
point() {
return valueToPoint(
this.stat.value,
this.index,
this.total
)
},
style() {
var angle = this.point.angle;
return {
transform: "rotate(" + angle + "rad)"
}
}
}
}
}
})
// math helper...
function valueToPoint(value, index, total) {
var maxV = 100
var maxR = 300 * 0.9
var r = maxR / maxV * value
var angle = Math.PI * 2 / total * index + Math.PI / 2
var cos = Math.cos(angle)
var sin = Math.sin(angle)
var tx = r * cos
var ty = r * sin
return {
angle: angle,
radius: r,
x: tx,
y: ty
}
}

Related

How to create a charjs bar graph with many bars?

I want to get the effect of something like this:
And here is my best attempt as a combo graph:
The problem is I need to vastly ramp up the number of bars in this chart. However, when I try to do this the bars disappear.
Here is my code as a typescript reactjs setup:
import './App.css';
import React from 'react';
import { Bar, Line } from 'react-chartjs-2';
const createRandomFollowersData = () => {
const maxDate = new Date();
const minDate = new Date(maxDate.valueOf() - 5 * 365 * 24 * 60 * 60 * 1000);
const dataPoints = Array.from({ length: 500 }).map(() => ({
timestamp: new Date(
Math.floor(Math.random() * (maxDate.valueOf() - minDate.valueOf())) +
minDate.valueOf()
).toISOString(),
followers: Math.floor(Math.random() * 1000000) + 0,
}));
return dataPoints.sort(
(a, b) => new Date(a.timestamp).valueOf() - new Date(b.timestamp).valueOf()
);
};
const createRandomAssetData = () => {
const maxDate = new Date();
const minDate = new Date(maxDate.valueOf() - 5 * 365 * 24 * 60 * 60 * 1000);
const dataPoints = Array.from({ length: 500 }).map(() => ({
timestamp: new Date(
Math.floor(Math.random() * (maxDate.valueOf() - minDate.valueOf())) +
minDate.valueOf()
).toISOString(),
price: Math.floor(Math.random() * 45) + 1,
}));
return dataPoints.sort(
(a, b) => new Date(a.timestamp).valueOf() - new Date(b.timestamp).valueOf()
);
};
const followersData = createRandomFollowersData();
const yAxisFollowers = {
type: 'linear',
id: 'followers',
};
const yAxisDelta = {
type: 'linear',
position: 'right',
id: 'change',
};
const yAxisRank = {
type: 'linear',
id: 'rank',
ticks: {
reverse: true,
},
};
const yAxisAssets = {
type: 'linear',
position: 'right',
id: 'assets',
};
const selectChartAxes = (
containsFollowers: boolean,
containsRank: boolean,
showDelta: boolean,
showAssets: boolean
) => {
const yAxes = [];
if (containsFollowers) yAxes.push(yAxisFollowers);
if (containsRank) yAxes.push(yAxisRank);
if (showDelta) yAxes.push(yAxisDelta);
if (showAssets) yAxes.push(yAxisAssets);
return yAxes;
};
const decimateChart = (
data: {
t: Date;
y: number;
}[],
numBuckets: number,
startDate?: Date,
endDate?: Date
) => {
if (!startDate) {
startDate = data[0].t;
}
if (!endDate) {
endDate = data[data.length - 1].t;
}
// create evenly spaced dates
const dt = endDate.valueOf() - startDate.valueOf();
const startValue = startDate.valueOf();
const spacedDates = Array.from({ length: numBuckets + 1 }).map((_, idx) => {
return new Date(startValue + (idx * dt) / numBuckets);
});
// make buckets
const buckets = Array.from({ length: numBuckets + 2 }).map(() => []) as {
t: Date;
y: number;
}[][];
const filteredData = data.filter(
(e) => e.t >= spacedDates[0] && e.t <= spacedDates[spacedDates.length - 1]
);
// place data into buckets
let jdx = 0;
spacedDates.forEach((e, idx) => {
for (; jdx < filteredData.length; ) {
const e = filteredData[jdx];
const date = new Date(e.t);
if (date >= spacedDates[idx] && date <= spacedDates[idx + 1]) {
buckets[idx].push({
t: date,
y: e.y,
});
++jdx;
} else break;
}
});
// one plot per bucket
return buckets.map((bucket, idx) => {
const date = spacedDates[idx];
if (bucket.length === 0) {
return {
t: date,
y: NaN,
};
}
return bucket[bucket.length - 1];
});
};
const chartMappedFollowersData = followersData.map((followerData) => ({
t: new Date(followerData.timestamp),
y: followerData.followers,
}));
// const decimatedData = decimateChart(chartMappedFollowersData, 75);
const decimatedData = decimateChart(chartMappedFollowersData, 75).map(
(e, idx) => {
if (idx > 1 && idx < 10) {
return {
t: e.t,
y: NaN,
};
}
if (idx > 30 && idx < 45) {
return {
t: e.t,
y: NaN,
};
}
return e;
}
);
const decimatedDataToBars = (
data: {
t: Date;
y: number;
}[]
) => {
if (data.length < 2) {
return {
t: data[0].t,
y: data[0].y,
};
}
const bars = [];
const indexedData = data.map((e, idx) => ({
...e,
idx,
}));
const filteredIndexedData = indexedData.filter((e) => !isNaN(e.y));
for (let idx = 0; idx < filteredIndexedData.length - 1; ++idx) {
const dt = data[idx + 1].t.valueOf() - data[idx].t.valueOf();
for (
let idy = 0;
idy < filteredIndexedData[idx + 1].idx - filteredIndexedData[idx].idx;
++idy
) {
const t = new Date(filteredIndexedData[idx].t.valueOf() + idy * dt);
const deltaY =
(filteredIndexedData[idx + 1].y - filteredIndexedData[idx].y) /
(filteredIndexedData[idx + 1].idx - filteredIndexedData[idx].idx);
bars.push({
t,
y: deltaY,
});
}
}
return bars;
};
const chartOptionsLinear = {
scales: {
yAxes: selectChartAxes(true, false, true, true),
xAxes: [
{
type: 'time',
time: {
unit: 'day',
displayFormats: { day: 'MMM DD, Y' },
min: chartMappedFollowersData[0].t,
max: chartMappedFollowersData[chartMappedFollowersData.length - 1].t,
},
ticks: {
source: 'labels',
},
},
],
maintainAspectRatio: false,
},
};
const chartData = {
labels: decimatedData.map((e) => e.t).filter((_, idx) => idx % 3 === 0),
datasets: [
{
yAxisID: 'followers',
cubicInterpolationMode: 'monotone',
backgroundColor: 'rgb(54, 162, 235)',
borderColor: 'rgb(88, 88, 88)',
fill: false,
type: 'line',
label: 'followers',
spanGaps: true,
data: decimatedData,
},
{
yAxisID: 'change',
type: 'bar',
backgroundColor: 'rgb(235, 54, 162)',
label: 'delta',
data: decimatedDataToBars(decimatedData),
barThickness: 1,
},
],
};
function App(): JSX.Element {
return (
<div style={{ margin: '1em' }}>
<Bar data={chartData} options={chartOptionsLinear} />
</div>
);
}
export default App;
If you swap out data: decimatedDataToBars(decimatedData), to data: decimatedDataToBars(chartMappedFollowersData), you can see the effect; The bars disappear. Does anyone have any insight into this problem and how I can fix it?
So the issue was a bug in 2.8.0 that caused the bars to not show. Upgrading to 2.9.4 fixed the issue for me (but broke some other functionality of why I was using 2.8.0 in the first place.)

Why highchart returning " Typeerror : undefined variable byte "?

I am trying to draw a graph with the help of high chart and also using load event I am trying to add values after each 1 second to the graph.
In this graph I also want to show axis as Mb,Kb,,Gb data. So I am writing a function to return the byte values as Mb,Kb,Gb (for both series and tooltip)
This is my code :
// highchart options :
var series1, series2 ;
var chart = {
type: 'bar',
events: {
load: function () {
// set up the updating of the chart each second
series1 = this.series[0];
series2 = this.series[1];
setInterval(function () {
add_function();
}, 1000);//call function each 1 second
}
}
};
var tooltip = {
enabled: true,
formatter: function() { return fbytes(this.y,2);}
};
var plotOptions = {
bar: {
},
series: {
dataLabels: {
enabled: true,
formatter: function() { return fbytes(this.y,2);},
inside: true,
style: {fontWeight: 'number'}
},
pointPadding: 0,
pointWidth:38
},
column : {
grouping: true
}
};
series= [
{
name: 'old',
color: '#f9a80e',
data: [,]
},
{
name: 'new',
color: '#89897f',
data: [,]
}
];
and the load event function is :
Array.max = function (array) {
return Math.max.apply(Math, array);
};
Array.min = function (array) {
return Math.min.apply(Math, array);
};
add_function()
{
var arr[];
//getting array values here
var min_value = Array.min(arr);
var max_value = Array.max(arr);
var chart2 = $('#container').highcharts();
chart2.yAxis[0].update({max:max_value, min: 0}, true);
series1.setData([arr[0],arr[2]], true, true);
series2.setData([arr[1],arr[3]], true, true);
}
and the conversion function :
function fbytes(bytes, precision) {
var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
var posttxt = 0;
if (bytes == 0) return '0 Bytes';
if (bytes < 1024) {
return Number(bytes) + " " + sizes[posttxt];
}
while( bytes >= 1024 ) {
posttxt++;
bytes = bytes / 1024;
}
return Math.round(bytes.toPrecision(precision)) + " " + sizes[posttxt];
}
my logic : i got some array values randomly and i am displaying this data on the graph .
problem facing : I didn't get this.y value inside series . When i print this value inside
series: {
dataLabels: {
enabled: true,
formatter: function() { return fbytes(this.y,2);},
inside: true,
style: {fontWeight: 'number'}
},
I am getting this.y = undefined . What is happening ?
Any mistake in the code ? Any suggestions ?
I created demo using your code and modified add_function() a little bit. Did you mean something like this?
function add_function(series1, series2) {
var chart2 = $('#container').highcharts(),
increment = 1024,
min_value,
max_value,
newVal1 = [],
newVal2 = [];
if (!series1.data.length && !series2.data.length) {
var arr = [512, 128, 1024, 0];
min_value = Array.min(arr);
max_value = Array.max(arr);
newVal1 = [arr[0], arr[2]];
newVal2 = [arr[1], arr[3]];
} else {
series1.yData.forEach(function(sEl, sInx) {
newVal1.push(sEl + increment);
});
series2.yData.forEach(function(sEl, sInx) {
newVal2.push(sEl + increment);
});
max_value = Array.max(newVal1.concat(newVal2));
}
chart2.yAxis[0].update({
max: max_value,
min: 0
}, true);
series1.setData(newVal1, true, true);
series2.setData(newVal2, true, true);
}
Example:
http://jsfiddle.net/js3g311q/

How to improve performance of Highcharts and avoid error 15 inspite of sorted data?

I am trying to create a gantt chart representation in highcharts with navigator. I get a JSON response from server (below is a typical response strucutre). In order to create a gantt chart representation I am creating a line between 2 points. Each point has a start_date and end_date and inorder to create this representation I am plotting a line between start_date and end_date of each point (which I have accomplished).
Response Structure from server
{
"took": 312,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
},
"hits": {
"total": 4115,
"max_score": 1,
"hits": [
]
},
"aggregations": {
"top-tags": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": [
{
"key": "Process1",
"doc_count": 6,
"process": {
"value": {
"1449878649000": {
"start_date": 1449878649000,
"process_initiator": "lol#surg.com",
"end_date": 1449878734000,
"total_seconds": 85
},
"1449879753000": {
"start_date": 1449879753000,
"process_initiator": "lol#surg.com",
"end_date": 1449879850000,
"total_seconds": 97
},
"1449881550000": {
"start_date": 1449881550000,
"process_initiator": "lol#surg.com",
"end_date": 1449881631000,
"total_seconds": 81
}
}
}
},
{
"key": "Process2",
"doc_count": 1,
"process": {
"value": {
"1449971262000": {
"start_date": 1449971262000,
"process_initiator": "lol#surg.com",
"end_date": 1449971266000,
"total_seconds": 4
}
}
}
}
]
}
}
}
Code also sharing a plunker demo
var app = angular.module('app', []);
app.directive('operationalhighstackstock', function() {
return {
restrict: 'E',
scope: true,
link: function postLink(scope, element, attrs) {
scope.$watch('operationHighChartsData', function(values) {
new Highcharts.StockChart(values);
});
}
};
});
//2014-11-30T18:15:25.000-08:00
app.controller('MainCtrl', ['$scope', function($scope) {
$scope.excludeValue = {
data: 0
};
$scope.isExcludeNeeded = true;
var opExcludeMinutes = 1,
AGENT_NAMES = "agent_names",
colorCodes = ["#8CC051", "#967BDC", "#5D9CEC", "#FB6E52", "#EC87BF", "#46CEAD", "#FFCE55", "#193441", "#193441", "#BEEB9F", "#E3DB9A", "#917A56"];
var setSummaryDisplay = function(e) {
if (e.min === null || e.max === null)
$scope.hideRangeSlider = true;
else
$scope.hideRangeSlider = false;
$scope.minimumSelectedValue = e.min;
$scope.maximumSelectedValue = e.max;
}
var getHichartsData = function(result) {
var tasksArr = [],
seriesArr = [],
userArr = [],
processArr = [];
var agentSeries = [],
agentData = {},
processSeries = [],
taskData = {},
idx = 0,
opProcessBucket = esResponse.aggregations["top-tags"].buckets,
seriesData = {};
var opBucketLength = opProcessBucket.length;
for (var opProcessBucketIndex = 0; opProcessBucketIndex < opBucketLength; ++opProcessBucketIndex) {
//opProcessBucket.forEach(function(processEntry) {
//if (opProcessBucket[opProcessBucketIndex]["key"] == $scope.gpDropDownTitle) {
var intervalBucket = opProcessBucket[opProcessBucketIndex]["process"]["value"], //opProcessBucket[opProcessBucketIndex]["top_tag_hits"]["hits"]["hits"],
intervalArr = [],
tasksIntervalArr = [],
opTaskidObj = {},
opTaskidIntervalObj = {},
process_name = null,
sortElementArr = [];
for (var key in intervalBucket) {
//intervalBucket.forEach(function(intervalEntry, intervalIndex) {
var intervalObj = {},
intervalObj2ndpoint = {},
processIntervalObj = {},
tintervalArr = [],
intervalIndex = 0,
start_temp = parseInt(key),
end_temp = intervalBucket[key].end_date; //start_temp = intervalBucket[key].start_date, end_temp = intervalBucket[key].end_date;
//added here since response contains null value and data load will take almost 1 date, verified with Bhavesh
$scope.currentDateTime = new Date().getTime();
if (end_temp == null)
end_temp = $scope.currentDateTime;
var st = new Date(moment(start_temp).valueOf()).getTime();
var et = new Date(moment(end_temp).valueOf()).getTime();
var duration = moment.duration(moment(et).diff(moment(st)));
var minutes = duration.asMinutes();
if (minutes > $scope.excludeValue.data && $scope.isExcludeNeeded) {
if (intervalIndex == 0 || process_name == null) {
process_name = opProcessBucket[opProcessBucketIndex]["key"];
processArr.push(opProcessBucket[opProcessBucketIndex]["key"]);
}
userArr.push(intervalBucket[key].process_initiator);
processIntervalObj["task_id"] = opProcessBucket[opProcessBucketIndex]["key"];
processIntervalObj["from"] = st;
var lFromtime = moment.utc(st).toDate();
lFromtime = moment(lFromtime).format('MM/DD/YY HH:mm');
var lTotime = moment.utc(et).toDate();
lTotime = moment(lTotime).format('MM/DD/YY HH:mm');
processIntervalObj["to"] = et;
processIntervalObj["color"] = "#FFCC4E";
processIntervalObj["fromDateString"] = lFromtime;
processIntervalObj["toDateString"] = lTotime;
processIntervalObj["process_initiator"] = intervalBucket[key].process_initiator == null ? 'Unknown' : intervalBucket[key].process_initiator;
processIntervalObj["total_seconds"] = intervalBucket[key].total_seconds;
//sortElementArr.push(intervalEntry["sort"][0]);
tasksIntervalArr.push(processIntervalObj);
}
}
opTaskidObj["name"] = process_name;
opTaskidIntervalObj["name"] = process_name;
opTaskidObj["data"] = [];
opTaskidIntervalObj["intervals"] = tasksIntervalArr;
opTaskidIntervalObj["intervals"] = tasksIntervalArr;
idx++;
if (tasksIntervalArr.length > 0) {
processSeries.push(opTaskidIntervalObj);
agentSeries.push(opTaskidObj);
}
//}
}
seriesData["title"] = "Test"; //item["key"];
var series = [];
(processSeries.reverse()).forEach(function(task, i) {
var item = {
name: task.name,
data: [],
turboThreshold: 1100000
};
(task.intervals).forEach(function(interval, j) {
item.data.push({
task_id: interval.task_id,
x: interval.from,
y: i,
from: interval.from,
to: interval.to,
color: interval.color,
fromDateString: interval.fromDateString,
toDateString: interval.toDateString,
total_seconds: interval.total_seconds,
process_initiator: interval.process_initiator
}, {
task_id: interval.task_id,
x: interval.to,
y: i,
from: interval.from,
to: interval.to,
color: interval.color,
fromDateString: interval.fromDateString,
toDateString: interval.toDateString,
total_seconds: interval.total_seconds,
process_initiator: interval.process_initiator
});
// add a null value between intervals
if (task.intervals[j + 1]) {
item.data.push([(interval.to + task.intervals[j + 1].from) / 2, null]);
}
});
series.push(item);
})
seriesData["data"] = series;
seriesData["tasks"] = processSeries;
seriesArr.push(seriesData);
return seriesArr;
}
$scope.agentSeriesData = getHichartsData(esResponse);
var tasks = $scope.agentSeriesData[0].tasks;
var seriesData = $scope.agentSeriesData[0].data;
var xAxisStepping = 1 * 3600 * 1000;
var chart = new Highcharts.StockChart({
chart: {
renderTo: 'container',
height: 600,
events: {
load: function(e) {
var max = this.xAxis[0].max;
var range = (24 * 3600 * 1000) * 7; // one day * 7
if ($scope.isInit || $scope.filterReseted) {
$scope.filterReseted = false;
this.xAxis[0].setExtremes(max - range, max);
}
setSummaryDisplay.call(this.xAxis[0], {
trigger: "navigator",
min: this.xAxis[0].min,
max: this.xAxis[0].max
});
}
}
},
title: {},
credits: {
enabled: false
},
xAxis: {
type: 'datetime',
gridLineWidth: 1,
tickInterval: xAxisStepping,
//ordinal:false,
dateTimeLabelFormats: {
month: '%b %e, %Y'
},
events: {
afterSetExtremes: setSummaryDisplay
},
minRange: 1000
},
yAxis: {
tickInterval: 1,
gridLineWidth: 1,
labels: {
enabled: false,
formatter: function() {
if (tasks[this.value]) {
return tasks[this.value].name;
}
}
},
startOnTick: false,
endOnTick: false,
title: {
text: 'Process'
}
},
animation: false,
rangeSelector: {
enabled: false
},
navigator: {
enabled: true
},
legend: {
enabled: false
},
tooltip: {
shared: false,
formatter: function() {
var str = '';
str += 'Process: ' + this.series.name + '<br>';
str += 'From: ' + Highcharts.dateFormat('%m/%d/%y %H:%M:%S', this.point.from) + '<br>';
str += 'To: ' + Highcharts.dateFormat('%m/%d/%y %H:%M:%S', this.point.to) + '<br>';
return str;
}
},
plotOptions: {
line: {
lineWidth: 10,
marker: {
enabled: false
},
dataLabels: {
enabled: false,
borderRadius: 5,
borderWidth: 1,
y: -6,
formatter: function() {
return this.series.name;
}
},
states: {
hover: {
lineWidth: 10
}
}
},
series: {
cursor: 'pointer',
animation: false,
point: {
events: {
click: function() {
$scope.selectedGuide = this.series.name;
//$scope.showTableView();
}
}
},
turboThreshold: 100000000,
dataGrouping: {
enabled: false
}
}
},
scrollbar: {
enabled: false
},
series: seriesData
});
$scope.operationHighChartsData = chart;
}]);
I have sorted data (ascending order) but I am still getting Highcharts error #15: www.highcharts.com/errors/15 errors in thousands (mostly 80k +), which is hanging the browser.
What could be the issue and how can I get rid of it and increase performance? Sharing a plunker which has code and relatively small number of errors.
Note: I am using Highstock JS v2.1.5
There are two problems with this code:
First thing you need to sort the series in ascending order of X. I did not want to debug your code on how do you construct your data so I added a simple loop in the end to sort everything.
for (var i in seriesData) {
seriesData[i].data.sort(function(a, b) {
if (a.x > b.x) {
return 1;
}
if (b.x > a.x) {
return -1;
}
return 0;
});
}
The other problem is that the data array contains in correct data because of this line
if (task.intervals[j + 1]) {
item.data.push([(interval.to + task.intervals[j + 1].from) / 2, null]);
}
so I changed it to this
// add a null value between intervals
if (task.intervals[j + 1]) {
item.data.push({
task_id: interval.task_id,
x: (interval.to + task.intervals[j + 1].from) / 2,
y: null,
from: (interval.to + task.intervals[j + 1].from) / 2,
to: (interval.to + task.intervals[j + 1].from) / 2
});
}
here is the fixed plnkr
http://plnkr.co/edit/OEMuVfTMhHNQsTYGUyuy?p=preview
Please read this link to improve highcharts performance. A few months ago Highcharts released boost.js to improve chart performance with millions of data points.

Restacking cumulative columns in Highcharts marimekko charts

I've got a basic variable width column chart (aka Marimekko) set up using Highcharts but am having trouble getting it to restack the columns properly to eliminate the data gap once a series has been removed or hidden.
JSFIDDLE DEMO <-- I've set up a demo of the issue here.
You'll notice clicking on a legend item removes the series from the chart, but it also removes all of the following data points in the array (i.e. clicking on series C removes series C, D, and E whereas it should redraw to A-B-D-E). Since the y-axis data is meant to display a cumulative sum of all series, these should re-shuffle as adjacent columns with no gaps. How can I get this to render properly?
THIS POST uses similar demo code and attempting to solve the same problem, however the answer is somewhat elusive and I am unable to get it working.
Thanks in advance!
$(function () {
var dataArray = [
{ name: 'A', x: 200, y: 120 },
{ name: 'B', x: 380, y: 101 },
{ name: 'C', x: 450, y: 84 },
{ name: 'D', x: 198, y: 75 },
{ name: 'E', x: 95, y: 55 }
];
function makeSeries(listOfData) {
var sumX = 0.0;
for (var i = 0; i < listOfData.length; i++) {
sumX += listOfData[i].x;
}
var allSeries = []
var x = 0.0;
for (var i = 0; i < listOfData.length; i++) {
var data = listOfData[i];
allSeries[i] = {
name: data.name,
data: [
[x, 0], [x, data.y],
{
x: x + data.x / 2.0,
y: data.y,
dataLabels: { enabled: false, format: data.x + ' x {y}' }
},
[x + data.x, data.y], [x + data.x, 0]
],
w: data.x,
h: data.y
};
x += data.x + 0;
}
return allSeries;
}
$('#container').highcharts({
chart: { type: 'area' },
xAxis: {
tickLength: 0,
labels: { enabled: true}
},
yAxis: {
title: { enabled: false}
},
plotOptions: {
series: {
events: {
legendItemClick: function () {
var pos = this.index;
var sname = this.name;
var chart = $('#container').highcharts();
while(chart.series.length > 0) {
chart.series[pos].remove(true);
}
dataArray[pos]= { name: sname, x: 0, y: 0 };
chart.series[0].setData(dataArray);
}
}
},
area: {
lineWidth: 0,
marker: {
enabled: false,
states: {
hover: { enabled: false }
}
}
}
},
series: makeSeries(dataArray)
});
});

Creating Highchart Graph with JavaScript

I want to create high chart graph .
Here is FIDDLE LINK of My code.
I am giving two values a and b . a for x-axis b for y-axis. Problem is that when i gave values of a and b . when the difference between a and b is less, then no graph appears
i-e. a= -9 , b= -9 . Otherwise it works
$(function () {
var a, b, x, j;
a = -9;
b = -9;
if (a > b) {
x = a;
j = b
} else {
x = b;
j = a
}
alert("X is " + x);
alert("Y is" + j);
$('#container').highcharts({
chart: {
type: 'bar',
backgroundColor: null
},
credits: {
enabled: false
},
tooltip: {
enabled: false,
},
title: {
text: ''
},
xAxis: {
categories: ["", "", ""],
//minTickInterval:20000,
},
yAxis: {
min: j - (j * 5 / 100),
max: x + (x * 5 / 100),
//min: -50,
//max: -50,
//minTickInterval:20000,
endOnTick: true,
tickPixelInterval: 340,
maxPadding: 0.25,
title: {
text: ''
},
labels: {
formatter: function () {
if (j - (j * 5 / 100) > 1000000) {
return Highcharts.numberFormat((this.value) / 1000000, 0, '', ',') + 'M';
} else if (j - (j * 5 / 100) > 1000) {
return Highcharts.numberFormat((this.value) / 1000, 0, '', ',') + 'K';
} else {
return Highcharts.numberFormat((this.value), 0, '', ',');
}
},
x: 6
}
},
legend: {
backgroundColor: '#FFFFFF',
reversed: true
},
plotOptions: {
series: {
stacking: 'normal'
}
},
series: [{
name: ' ',
data: [a]
},
{
name: ' ',
data: [0, b]
}, ]
});
});
Here's a working fiddle
Just remove:
min: j-(j*5/100),
max: x+(x*5/100)
from the yAxis: { --- some options --- }
Also try this with one value positive and other negative for a and b.
Hope this helps.

Categories

Resources