Highcharts percentage variability position - javascript

While percentage of each piece of pie chart reach 50%( or 52% and 48%) the position of percentage is changed, namely is not the same when was 16% and 84% each piece of graph.
The code that I use is:
Highcharts.chart('container1', {
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: 'pie',
options3d: {
enabled: true,
alpha:70,
beta: 0
}
},
title: {
text: ''
},
plotOptions: {
pie: {
allowPointSelect: false,
cursor: 'pointer',
size:100,
depth: 15,
dataLabels: {
textOverflow:'none',
enabled: true,
color:'black',
connectorColor:'transparent',
format:'{point.percentage:.1f}%',
distance:-30,
style:{
textShadow:false}
},
showInLegend: false
}
},
series: [{
type: 'pie',
name: 'ΑΞΚΟΙ - ΑΝΘΣΤΕΣ',
data: [
['Παρόντες', <?php
while ($row2 = mysql_fetch_assoc($res2)) {
while( $row1 = mysql_fetch_assoc($res1)){
$row3['COUNT(*)']=$row2['COUNT(*)'] - $row1['COUNT(*)'];
echo $row3['COUNT(*)'];
}
}?>],
['Απόντες', <?php
while( $row3 = mysql_fetch_assoc($res3)){
echo $row3['COUNT(*)'];
}
?>]
]
}]
});
There is a feature that can I use in order to make position of percentage constant?
Thanks in advance

You can set fixed position of the data labels by calling Highcharts.SVGElement.attr() function on each label:
events: {
load: function() {
var points = this.series[0].points;
points.forEach((p) => p.connector.destroy()); // destroy connectors
// set fixed position for both points
points[0].dataLabel.attr({
x: 300,
y: 100
});
points[1].dataLabel.attr({
x: 75,
y: 100
});
}
}
Live demo: http://jsfiddle.net/kkulig/8z3g1LLy/
API reference: https://api.highcharts.com/class-reference/Highcharts.SVGElement#attr

Related

HighCharts inside of a javascript function

I'm trying to draw a 3d box after a user has selected some data from the server.
When I put the highcharts inside of a js function, it throws some errors.
My code is:
Chart It<br/>
<div id="container" style="height: 400px"></div>
<script>
var chart;
function chart3d() {
// Give the points a 3D feel by adding a radial gradient
Highcharts.getOptions().colors = $.map(Highcharts.getOptions().colors, function (color) {
return {
radialGradient: {
cx: 0.4,
cy: 0.3,
r: 0.5
},
stops: [
[0, color],
[1, Highcharts.Color(color).brighten(-0.2).get('rgb')]
]
};
});
// Set up the chart
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
margin: 100,
type: 'scatter',
options3d: {
enabled: true,
alpha: 10,
beta: 30,
depth: 250,
viewDistance: 5,
fitToPlot: false,
frame: {
bottom: {
size: 1,
color: 'rgba(0,0,0,0.02)'
},
back: {
size: 1,
color: 'rgba(0,0,0,0.04)'
},
side: {
size: 1,
color: 'rgba(0,0,0,0.06)'
}
}
}
},
title: {
text: 'Draggable box'
},
subtitle: {
text: 'Click and drag the plot area to rotate in space'
},
plotOptions: {
scatter: {
width: 10,
height: 10,
depth: 10
}
},
yAxis: {
min: 0,
max: 10,
title: null
},
xAxis: {
min: 0,
max: 10,
gridLineWidth: 1
},
zAxis: {
min: 0,
max: 10,
showFirstLabel: false
},
legend: {
enabled: false
},
series: [{
planeProjection: {
enabled: false,
},
lineProjection: {
enabled: 'hover',
colorByPoint: true
},
name: 'Reading',
colorByPoint: true,
data: darray
}]
});
// Add mouse events for rotation
$(chart.container).on('mousedown.hc touchstart.hc', function (eStart) {
eStart = chart.pointer.normalize(eStart);
var posX = eStart.pageX,
posY = eStart.pageY,
alpha = chart.options.chart.options3d.alpha,
beta = chart.options.chart.options3d.beta,
newAlpha,
newBeta,
sensitivity = 5; // lower is more sensitive
$(document).on({
'mousemove.hc touchdrag.hc': function (e) {
// Run beta
newBeta = beta + (posX - e.pageX) / sensitivity;
chart.options.chart.options3d.beta = newBeta;
// Run alpha
newAlpha = alpha + (e.pageY - posY) / sensitivity;
chart.options.chart.options3d.alpha = newAlpha;
chart.redraw(false);
},
'mouseup touchend': function () {
$(document).off('.hc');
}
});
});
}
</script>
This loads fine if I do not put it inside of the chart3d function. Is there a way to get this working. The error message I get is:
highcharts.js:10 Uncaught Error: Highcharts error #13: www.highcharts.com/errors/13
at Object.a.error (highcharts.js:10)
at a.Chart.getContainer (highcharts.js:256)
at a.Chart.firstRender (highcharts.js:271)
at a.Chart.init (highcharts.js:247)
at a.Chart.getArgs (highcharts.js:246)
at new a.Chart (highcharts.js:246)
at chart3d (graphingCustom.js:26)
at HTMLAnchorElement.onclick (VM599 :643)
As they say:
Highcharts Error #13
Rendering div not found
This error occurs if the chart.renderTo option is misconfigured so that
Highcharts is unable to find the HTML element to render the chart in.
You don't have a div with the id=container at the time you are calling the method.

how to show mutipal dynamic highcharts based on json data

I want to use json data to construct mutipal pie charts. And put the pie chart inside class container, so for example:
data.data[0].usedPercentage=0,
data.data[1].usedPercentage=20,
data.data[2].usedPercentage=0,
the output pie chart should display like 0%, 20%, 0% ,
but now they display the same all in 0%, could anybody give some clues about that? Thanks a lot
$.ajax({
type: "GET",
url: 'http://XXX.XXX.XXX.XX',
dataType:'json',
contentType:"application/json",
success:function(data){
console.log(data);
var used = new Array();
for (var i = 0; i < data.data.length; i++) {
used[i]=data.data[i].usedPercentage;
pieIndex(used[i]);
projectList +="<div class='container'>pie</div>"
function pieIndex(used){
$(function () {
// Using classes to select multiple containers
var $containers = $(".container");
// You just set the configuration object once
var chartConfig = {
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: 'pie'
},
title: {
text: ''
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: false
},
showInLegend: true
}
},
series: [{
name: 'precentage',
colorByPoint: true,
data: [{
name: 'Unused',
y: 100-Number(used),
color: '#eeeeee',
sliced: true,
selected: true
}, {
name: 'Used',
y: Number(used),
color: '#f34s12',
selected: true
}]
}]
};
$containers.each(function() {
$(this).highcharts(chartConfig);
});
});
}
},
error:function(){
alert("connection error");
}
});
});
Each chart need a unique id on the container. Looks like you are overwriting those containers with the last chart. Try using a different id on each container div. For example:
projectList +="<div id='pie-chart-container-" + i + "' class='container'>pie</div>"

Draw piechart with highcharts using php array of data

I want to replace PHP array $os_array with JavaScript variable to send with different values. Like as var x =<?php echo $os_array; ?>; drawcharts($x); when alert var x result will be ['Internet Explorer 7',1],['Internet Explorer 8',1],['Outlook 2007',2]
var x="<?php echo $os_array;?>";
drawcharts(x);
function drawcharts(x){
$('#_shared_graphs').highcharts({
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
backgroundColor: '#f1f1f1'
},
title: {
text: 'OS'
},
tooltip: {
pointFormat: '{point.y} Using <b>{point.name}'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {point.percentage:.1f} %',
style: {
color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
}
}
}
},
series: [{
type: 'pie',
name: 'Sent Messag stat',
data: [x]
}]
});
}
well just define your js fkt:
function drawcharts(x) {
$('#_shared_graphs').highcharts({
...
series: [{
...
data: x
}]
});
}
then
var x =<?php echo json_encode($os_array); ?>;
drawcharts(x);
// reassign x
x = [ .... ];
drawcharts(x);

How to add multiple series dynamically and update its data dynamically

my task is to add series dynamically and keep updating their data, which is received by ajax calls.
i know series can be added dynamically by declaring highchart funciton global. and using series.addseries() function , and also data can be updated by using settimout request to ajax call and updating points by using series.addpoint() function.
i have done both the work separably. but when i combine both the technique, data is not added to highchart. i have done lot of research on this, and i am not finding reason for not adding the data. infact script hang the browser.
i have checked the series object, which show x-data and y-data are processed. only difference i find is isDirty field and isDirtydata field are set to true. dont know the reason.
here is the full code
var serverUrl = 'http://'+window.location.hostname+':8000'
Highcharts.setOptions({
global: {
useUTC: false
}
});
data={}
$(document).ready(function(){
$(function () {
console.log("highcharts")
$('#first').highcharts({
chart: {
type: 'spline',
//marginRight: 150,
marginBottom: 5,
events: {
load: requestData(data)
}
},
title: {
text: 'Server Monitroting Tool'
},
subtitle: {
text: 'Cpu usage, Memory Usage,Disk Usage,Mongo Usage'
},
xAxis: {
type: 'datetime',
categories: ['TIME'],
dateTimeLabelFormats : {
hour: '%I %p',
minute: '%I:%M %p'
}
},
yAxis:{
showEmpty:false
},
legend:
{
backgroundColor: '#F5F5F5',
layout: 'horizontal',
floating: true,
align: 'left',
verticalAlign: 'bottom',
x: 60,
y: 9,
shadow: false,
border: 0,
borderRadius: 0,
borderWidth: 0
},
series: {}
});
});
from_date=new Date().getTime()-60000;
function requestData(data)
{
if(!data)
{
console.log("default ")
}
else
{
console.log("requesting")
$.ajax({
url:serverUrl+'/api/fetch_params/',
type:'GET',
data:data,
success:function(response)
{
console.log("in success")
//data = {'type':TypeOfParameter,'hostname':hostname,'sub-type':sub_type,'param':sub_type_parameter,'from-date':from_date}
var id=data['sub-type']+data['param']
var series = chart.get(id)
shift = series.data.length > 100; // shift if the series is longer than 300 (drop oldest point)
response= $.parseJSON(response)
var x=data['sub-type']
all_data=response.response.data[x]
// console.log(new Date(from_date),'latest timestamp')
console.log(series)
console.log("data",all_data)
from_date=all_data[all_data.length-1][0]
// console.log(from_date)
// series.isDirty=false
// series.isDirtyData=false
for (var i = 0; i < all_data.length; i++)
{
series.addPoint({ x: all_data[i][0],y: all_data[i][1],id: i},false,shift);
}
console.log("series object",series)
// chart.redraw();
console.log(" parameter",data)
data['from-date']=from_date
console.log("data",series.data)
// console.log(chart)
setTimeout(requestData(data), 10000);
console.log("out of success")
},
cache:false,
error:function()
{
console.log("err")
}
});
}
}
$.ajax({
url:serverUrl+'/api/fetch_all_servers/',
type:'GET',
success:function(response){
response = $.parseJSON(response)
sd = response.response.all_servers
$('input[name=select_menue]').optionTree(sd)
},
error:function(){
console.log('error')
}
});
$('.param-button').live('click',function(e){
e.stopPropagation()
})
$('param-select').live('hover',function(){
$(this).find('.type-select').show()
});
$('.final_value').live('change',function(){
select_name = 'select_menue_'
param_list = []
var param=$('select[name="'+select_name+'"] option:selected').attr('value')
while(param){
param_list.push(param)
select_name += '_'
var param=$('select[name="'+select_name+'"] option:selected').attr('value')
}
console.log(param_list,"param_list")
from_date=new Date().getTime()-300000 //5 minute data
hostname=param_list[0]
TypeOfParameter= param_list[1]
sub_type_parameter=param_list[param_list.length-1]
data = {'type':TypeOfParameter,'hostname':hostname,'param':sub_type_parameter,'from-date':from_date}
var sub_type;
if(param_list.length==4){
sub_type=param_list[2]
data['sub-type'] = sub_type
}
else
{
sub_type=sub_type_parameter
}
// console.log(hostname,TypeOfParameter,sub_type,sub_type_parameter)
data = {'type':TypeOfParameter,'hostname':hostname,'sub-type':sub_type,'param':sub_type_parameter,'from-date':from_date}
requestData(data)
$('#loadingmessage').show(); // show the loading message.
chart = $('#first').highcharts();
if(TypeOfParameter=='cpu')
{
console.log("adding axis")
chart.addAxis({ // Primary yAxis
id:'Cpu_axis'+sub_type_parameter,
labels: {
formatter: function() {
return this.value;
},
style: {
color: '#89A54E'
}
},
title: {
text: "core "+ sub_type+ " "+sub_type_parameter,
style: {
color: '#89A54E'
}
},
lineWidth: 1,
lineColor: '#08F'
});
console.log("adding series")
chart.addSeries({
id:sub_type+sub_type_parameter,
name: "core "+sub_type+" "+sub_type_parameter,
data :[],
tooltip : {
valueSuffix: ' %'
},
yAxis:'Cpu_axis'+sub_type_parameter
})
console.log("series out")
}
if(TypeOfParameter=='memory')
{
chart.addAxis ({
id:'memory'+sub_type_parameter,
labels:{
formatter: function() {
return this.value +'%';
},
style: {
color: '#89C54F'
}
},
title: {
text:sub_type+" "+sub_type_parameter
},
lineWidth: .5,
lineColor: '#08F',
opposite: true
});
chart.addSeries({
id:sub_type+sub_type_parameter,
name: sub_type+'memory usage',
data: [],
tooltip: {
valueSuffix: '%'
},
yAxis:'memory'+sub_type_parameter
});
}
if(TypeOfParameter=='disk')
{
chart = new Highcharts.Chart({
chart: {
renderTo: 'second',
defaultSeriesType: 'spline',
events: {
load: requestData
}
},
title: {
text: 'disk Usage'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000
},
yAxis: {
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: 'disk',
margin: 80
}
},
series: [{
id:sub_type+sub_type_parameter,
name: 'disk',
data: []
}]
});
}
if(TypeOfParameter=='db')
{
chart = new Highcharts.Chart({
chart: {
renderTo: 'second',
defaultSeriesType: 'spline',
events: {
load: requestData
}
},
title: {
text: 'mongo Usage'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000
},
yAxis: {
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: 'mmongo',
margin: 80
}
},
series: [{
id:sub_type+sub_type_parameter,
name: 'mongo',
data: []
}]
});
}
if(TypeOfParameter=='redis')
{
chart = new Highcharts.Chart({
chart: {
renderTo: 'second',
defaultSeriesType: 'spline',
events: {
load: requestData
}
},
title: {
text: 'redis Usage'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000
},
yAxis: {
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: 'redis',
margin: 80
}
},
series: [{
id:sub_type+sub_type_parameter,
name: 'redis',
data: []
}]
});
}
$('#loadingmessage').hide(); // hide the loading message
}
)
});
i am stuck on this problem for quite a while. and still not able to figure out the solution.
here is the full code link
someone please please help. feeling frustrated ..:-(
As you know the addPoint method is bit dangerous when dealing with quite lots points. It is recommended to disable redraw per point when dealing with many new points - more info http://api.highcharts.com/highcharts#Series.addPoint() , I notice you are doing that already in the loop statement, but why did you commented out? have you tried enabling again. Make sure chart.redraw works by adding a new redraw chart event, and set an alert or console log.
Also you may try using, below as part of ajax, instead of cache:false. I had some problems in past.
headers: { 'Cache-Control': 'no-cache' }
Cheers

Add start-date and end-date as a Xaxis label in highchart

I use date as a string in my chart.
How can I use my start-date and end-date string variables as a label in my xAxis?
start-date = '10.02.2013'
end-date = '10.05.2013'
The code and the chart image is attached. The only thing I need to do is to add startDateLabel and endDateLabel.
var dateEndLabel, dateStartLabel, i, j, lastDate, seriesData, x, y;
i = 0;
seriesData = new Array();
lastDate = data[i].Values.length - 1;
dateStartLabel = data[i].Values[0].Time;
dateEndLabel = data[i].Values[lastDate].Time;
while (i < data.length) {
seriesData[i] = [];
j = 0;
x = [];
y = [];
while (j < data[i].Values.length) {
x = data[i].Values[j].Time;
y = data[i].Values[j].Value;
seriesData[i].push([x, y]);
j++;
}
i++;
}
return $("#criticalWPtrend").highcharts({
chart: {
type: "line"
},
area: {
height: "100%",
width: "100%",
margin: {
top: 20,
right: 30,
bottom: 30,
left: 50
}
},
title: {
text: ""
},
subtitle: {
text: ""
},
legend: {
layout: "vertical",
verticalAlign: "right",
align: "right",
borderWidth: 0
},
xAxis: {
type: 'datetime',
dateTimeLabelFormats: {
day: '%m-%d'
},
tickInterval: 24 * 3600 * 1000
},
yAxis: {
title: {
text: 'Value'
},
lineWidth: 1,
min: 0,
minorGridLineWidth: 0,
gridLineWidth: 0,
alternateGridColor: null
},
tooltip: {
valueSuffix: " "
},
plotOptions: {
series: {
marker: {
enabled: false
},
stickyTracking: {
enabled: false
}
},
line: {
lineWidth: 2,
states: {
hover: {
lineWidth: 3
}
},
marker: {
enabled: false
}
}
},
series: [
{
name: data[0].Name,
data: seriesData[0]
}, {
name: data[1].Name,
data: seriesData[1]
}, {
name: data[2].Name,
data: seriesData[2]
}, {
name: data[3].Name,
data: seriesData[3]
}, {
name: data[4].Name,
data: seriesData[4]
}, {
name: data[5].Name,
data: seriesData[5]
}
],
navigation: {
menuItemStyle: {
fontSize: "10px"
}
}
});
});
Yes, this is possible with the renderer method. See this basic example.
chart.renderer.text('10.02.2013', 0, 300)
.attr({
rotation: 0
})
.css({
color: '#4572A7',
fontSize: '16px'
})
.add();
You are going to need to pay attention to the x/y locations (the 2 other params) to place it correctly. You can also modify the text styling.
I'm not sure, but i think you just need to update your xAxis by update method
this.xAxis[0].update({
title: {
text: "start-date = '10.02.2013' end-date = '10.05.2013'",
style: {
fontSize: '10px'
}
}
});
Here's example: http://jsfiddle.net/FEwKX/
But!
If your mean that the start and end dates need to tie to edges, you must specify xAxis settings in config
xAxis: {
categories: categoriesArray
}
where categoriesArray is array like this:
['10.02.2013', '', '', '', '', '', '', '', '', '', '', '10.05.2013']
It should be the same lenght as your lenght of series data.
Check out here: http://jsfiddle.net/FEwKX/1/
Hope that'll help you.
You can also use labelFormatter and http://api.highcharts.com/highcharts#xAxis.labels.formatter and check if labels isFirst or isLast then use your dates, in other cases return proper value (like number).

Categories

Resources