Flot chart tooltip - javascript

I am using Flot interactive chart, the data being displayed is taken in from a datatable.
When the user hover's over a point the tooltip displays "Height(cm) on 6.00 = 168", basically the "168" represents the y value which is correct as it corresponds with the y-axis labels.
However the "6.00" should be a date, as is displayed on the chart along the x-axis, "6.00" is the sequence number , I need to get the label.....
any ideas ?
//Show ToolTip Part 2
function showTooltip(x, y, contents)
{
$('<div id="tooltip">' + contents + '</div>').css(
{
position: 'absolute',
display: 'none',
top: y + 5,
left: x + 15,
border: '1px solid #333',
padding: '4px',
color: '#fff',
'border-radius': '3px',
'background-color': '#333',
opacity: 0.7
}
).appendTo("body").fadeIn(400);
}
//Show ToolTip Part 1
var previousPoint = null;
$("#VitalsChart").bind("plothover", function (event, pos, item)
{
$("#x").text(pos.x.toFixed(2));
$("#y").text(pos.y.toFixed(2));
if (item)
{
if (previousPoint != item.dataIndex)
{
previousPoint = item.dataIndex;
$("#tooltip").remove();
var x = item.datapoint[0].toFixed(2),
y = item.datapoint[1].toFixed(2);
showTooltip(item.pageX, item.pageY, item.series.label + " on " + x + "=" + "<strong>" + y + "</strong>");
}
}
else
{
$("#tooltip").remove();
previousPoint = null;
}
});
//Plot Data
var plot = $.plot($("#VitalsChart"), [{ data: weight, label: "Weight (kg)" },
{ data: height, label: "Height (cm)" }],
{
series:
{
lines:
{
show: true,
lineWidth: 2,
fill: false,
fillColor: { colors: [{ opacity: 0.5 }, { opacity: 0.1 }] }
},
points: { show: true },
shadowSize: 7
},
grid:
{
hoverable: true,
clickable: false,
tickColor: "#ddd",
borderWidth: 1,
minBorderMargin: 10
},
colors: ["red", "blue"],
xaxis:
{
ticks: xLabels,
tickDecimals: 0
},
yaxis:
{
ticks: 11,
tickDecimals: 0
}
});
}

Try:
var x = xLabels[item.datapoint[0] - 1][1];
Your ticks (xLabels) is an array of 2 element arrays. You need just the second element, the label itself.

Related

Highcharts: render color to series dynamically

Problem: I am trying to plot a dumbel chart using highcharts. I want to conditionally check if the series is positive or negative and assign the color to the line series.
tried: to write a function to dynamically assign the colors but it does not work. But the same function is used to dynalically render circles and it work
https://jsfiddle.net/z4t2qg5o/
Highcharts.chart('container', {
chart: {
type: 'xrange'
},
plotOptions: {
columnrange: {
colorByPoint: true,
colors: ['red', 'blue', 'yellow']
}
},
title: {
text: 'Highcharts X-range'
},
xAxis: {
},
yAxis: {
title: {
text: ''
},
categories: ['Prototyping', 'Development', 'Testing'],
reversed: true
},
series: [{
// name: 'Project 3',
// pointPadding: 0,
// groupPadding: 0,
//borderColor: 'gray',
pointWidth: 5,
data: [{
x: 32,
x2: 33,
y: 0,
val: -1,
//color:'red'
// partialFill: 0.25
}, {
x: 21,
x2:25,
y: 1,
val: 1,
//color:'#BADA55'
}, {
x:31,
x2: 32,
y: 2,
val: -1,
//color:'red'
}],
dataLabels: {
align: 'left',
enabled: false
}
}]
}, function() {
var chart = this,
leftOffset = chart.plotLeft,
topOffset = chart.plotTop,
series = chart.series[0],
xAxis = series.xAxis,
x2Axis = series.x2Axis,
yAxis = series.yAxis,
points = series.points;
points.forEach(function(point) {
var x = xAxis.toPixels(point.x) - leftOffset,
x2 = xAxis.toPixels(point.x2) - leftOffset,
y = yAxis.toPixels(point.y - 0.005) - topOffset,
toCenter = x2-x;
val = point.val;
toCenter = toCenter > 0 ? toCenter : -toCenter;
if(val > 0 ){
//to set the color of the line to green
point.color = '#BADA55';
chart.renderer.circle(x, y, 6).attr({
fill: '#BADA55',
//'stroke-width': 1,
stroke: '#BADA55',
zIndex: 10
}).add(series.group);
chart.renderer.circle(x2, y, 6).attr({
fill: '#BADA55',
//'stroke-width': 1,
stroke: '#BADA55',
zIndex: 10
}).add(series.group);
// toCenter = toCenter > 0 ? toCenter : -toCenter;
chart.renderer.image('https://www.highcharts.com/samples/graphics/sun.png',x2 + 74,y +35,20,20).attr({
zIndex: 15
}).add();
}
else{
//to set the color of the line to green
point.color = '#BADA55';
chart.renderer.circle(x, y, 6).attr({
fill: '#ff0000',
'stroke-width': 1,
zIndex: 10
}).add(series.group);
chart.renderer.image('https://www.highcharts.com/samples/graphics/sun.png',x + 92,y +35,20,20).attr({
zIndex: 15
}).add();
// toCenter = toCenter > 0 ? toCenter : -toCenter;
chart.renderer.circle(x2, y , 6).attr({
fill: '#ff0000',
// 'stroke-width': 2,
zIndex: 10
}).add(series.group);
}
});
});
#container {
min-width: 300px;
max-width: 800px;
height: 300px;
margin: 1em auto;
}
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/xrange.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<div id="container"></div>
Expected: In the link shared, I want the line to be green when the 'val' is positive and the line to be red when the 'val' is negative
There might be a better way to achieve what you want. instead of writing your own function use Zones.
Look here.
You can use zones like this :
series:[{
data : [1,5,-8,9,12]//your data
zones : [{value:0,color:'red'},{color:'green'}]
}]
A live example of this is provided by HighCharts API refrence at this jsfiddle.
I don't know if this counts as an answer to your question but taking a look at this Zone thing might buy you some time.

Passing a PHP variable into flot Bar chart

I am trying to implode my php variable which is an array as one variable into my flot chart.
I implode my PHP variable with JS chart and it worked for me as you can see in the image :
I am trying to get Flot bar data same output with JS Bar chart. Any idea please ?
Thank you
var data = [ 0, <?php echo '['.implode(", ", $studentages).']'?>];
var dataset = [
{ label: "Exams By Student Age", data: data, color: "#5482FF" }
];
var ticks = [ [0, "0-2"]
];
var options = {
series: {
bars: {
show: true
}
},
bars: {
align: "center",
barWidth: 0.6 ,
vertical: true ,
show:true
},
xaxis: {
axisLabel: "Exams By Student Ages",
axisLabelUseCanvas: true,
axisLabelFontSizePixels: 12,
axisLabelFontFamily: 'Verdana, Arial',
axisLabelPadding: 10,
tickLength:0,
ticks: ticks
},
yaxis: {
axisLabel: "Number of Exams",
axisLabelUseCanvas: true,
axisLabelFontSizePixels: 12,
axisLabelFontFamily: 'Verdana, Arial',
axisLabelPadding: 3,
max:20, tickSize:1,
tickFormatter: function (v, axis) {
return v;
}
},
legend: {
noColumns: 0,
labelBoxBorderColor: "#000000",
position: "nw"
},
grid: {
clickable: true,
borderWidth: 1,
backgroundColor: { colors: ["#ffffff", "#EDF5FF"] }
}
};
$(document).ready(function () {
$.plot($("#flot-placeholder"), dataset, options);
$("#flot-placeholder").UseTooltip();
});
function gd(year, month, day) {
return new Date(year, month, day).getTime();
}
var previousPoint = null, previousLabel = null;
$.fn.UseTooltip = function () {
$(this).bind("plotclick", function (event, pos, item) {
var links = [ '../../Chart/StudentTests/result.php'];
if (item)
{
//alert("clicked");
// window.location = (links[item.dataIndex]);
window.open(links[item.dataIndex], '_blank');
console.log(item);
}
else {
$("#tooltip").remove();
previousPoint = null;
}
});
};
function showTooltip(x, y, color, contents) {
$('<div id="tooltip">' + contents + '</div>').css({
position: 'absolute',
display: 'none',
top: y - 40,
left: x - 120,
border: '2px solid ' + color,
padding: '3px',
'font-size': '9px',
'border-radius': '5px',
'background-color': '#fff',
'font-family': 'Verdana, Arial, Helvetica, Tahoma, sans-serif',
opacity: 10
}).appendTo("body").fadeIn(200);
}
That's what I am getting after I used your code.
If $studentages is an array of integers, this means that
var data = [ 0, [1, 2, 3, 4, 5]];
This is not the correct format for flot data which expects an array of arrays.
So, try:
var data = $.map(<?php echo '['.implode(", ", $studentages).']'?>, function(val, idx){
return [[idx, val]];
});
var dataset = [
{ label: "Exams By Student Age", data: data, color: "#5482FF" }
];
var ticks = [ [0, "0-2"] ]; // expand this for each idx in data

Chart plotted with inverted fill

I getting a strange behaviour in my chart using JQuery Flot.
When I'm plotting an anual chart, the blue fill is inverted like the image below.
The Monthly chart it's OK.
CHART
CODE
var data2014 = [];
var result = [[[1388534400000, 120371436.81027323], [1356998400000,187385608.24066913]]];
var p = 1;
var i = 0;
for (i = 0; i < result.length; i++, p++) {
data2014.push({
label: "Receitas",
data: result[i],
xaxis: p
});
}
var dataMaxSplines = (new Date(new Date().getFullYear() + "/1/1")).getTime();
var graficoTipoSpLines = {
series: {
splines: {
show: true,
tension: 0.19,
lineWidth: 1,
fill: 0.4
},
points: {
radius: 2,
show: true
},
shadowSize: 2
},
grid: {
hoverable: true,
clickable: true,
tickColor: "#d5d5d5",
borderWidth: 1,
color: "#d5d5d5"
},
colors: ["#00508F", "#F47920"],
xaxes: [
{
mode: "time",
tickSize: [1, "year"],
tickLength: null,
colors: ["#838383", "#838383"],
timeformat: "%Y",
max: dataMaxSplines
},
{
ticks: false
}
],
yaxis: {
ticks: 4,
tickFormatter: function (val, axis) {
if (val > 999999) {
return val.toString().replace(/\d{6}$/, "M");
} else if (val > 999 && val <= 999999) {
return val.toString().replace(/0{3}$/, 'K');
} else {
return val;
}
}
},
legend: {
backgroundOpacity: 0.5,
noColumns: 1,
position: "nw",
color: "#000000 !important"
}
}
$.plot($("#container"), data2014, graficoTipoSpLines);
http://jsfiddle.net/fbknhrk5/1/
In the series options replace splines with lines. See this updated fiddle.

Hide Series on Click with jQuery Flot

I have a Flot graph which I am trying to make it so that when you click a particular legend item it makes that data disappear from the chart.
I am having limited success in getting this to work. I've gotten as far as being able to click a legend item and a series line is removed, but not the points, and it appears to be the wrong line data as well.
Any help on this would be really appreciated :)
var Graphs = function () {
return {
//main function
initCharts: function () {
if (!jQuery.plot) {
return;
}
function showChartTooltip(x, y, xValue, yValue) {
$('<div id="tooltip" class="chart-tooltip">' + yValue + '<\/div>').css({
position: 'absolute',
display: 'none',
top: y - 40,
left: x - 40,
border: '0px solid #ccc',
padding: '2px 6px',
'background-color': '#fff'
}).appendTo("body").fadeIn(200);
}
if ($('#site_revenue').size() != 0) {
//site revenue
var previousPoint2 = null;
var plot_statistics = null;
var data = [];
togglePlot = function(seriesIdx)
{
var previousPoint2 = plot_statistics.getData();
previousPoint2[seriesIdx].lines.show = !previousPoint2[seriesIdx].lines.show;
plot_statistics.setData(previousPoint2);
plot_statistics.draw();
}
$('#site_revenue_loading').hide();
$('#site_revenue_content').show();
var data = [{
label: "Gross Revenue",
color: ['#44b5b1'],
points: {
fillColor: "#44b5b1"
},
data: [
['Sep', 264.41],
['Aug', 6653.98],
['Jul', 921.35],
['Jun', 937.00],
['May', 1839.25],
['Apr', 1561.96],
['Mar', 2289.62],
['Feb', 2661.91],
['Jan', 6021.44],
['Dec', 4129.21],
['Nov', 0.00],
['Oct', 2865.28],
],
idx:1
},{
label: "Tax",
color: ['#8fc2ed'],
points: {
fillColor: "#8fc2ed"
},
data: [
['Sep', 0.00],
['Aug', 2865.28],
['Jul', 2661.91],
['Jun', 6653.98],
['May', 6021.44],
['Apr', 0.00],
['Mar', 2289.62],
['Feb', 1561.96],
['Jan', 921.35],
['Dec', 937.00],
['Nov', 1839.25],
['Oct', 4129.21]
],
idx: 2
}];
var plot_statistics = $.plot($("#site_revenue"), data, {
series: {
lines: {
show: true,
fill: 0.2,
lineWidth: 0,
fill: false,
lineWidth: 3
},
shadowSize: 1,
points: {
show: true,
fill: true,
radius: 4,
lineWidth: 2
},
},
xaxis: {
tickLength: 0,
tickDecimals: 0,
mode: "categories",
min: 0,
font: {
lineHeight: 18,
style: "normal",
variant: "small-caps",
color: "#6F7B8A"
}
},
yaxis: {
ticks: 5,
tickDecimals: 0,
tickColor: "#eee",
font: {
lineHeight: 14,
style: "normal",
variant: "small-caps",
color: "#6F7B8A"
}
},
grid: {
hoverable: true,
clickable: true,
tickColor: "#eee",
borderColor: "#eee",
borderWidth: 1
},
legend: {
show: true,
placement: 'outsideGrid',
container: $('#site_revenue_legend'),
labelFormatter: function(label, series){
return ''+label+'';
}
}
});
$("#site_revenue").bind("plothover", function (event, pos, item) {
$("#x").text(pos.x.toFixed(2));
$("#y").text(pos.y.toFixed(2));
if (item) {
if (previousPoint2 != item.dataIndex) {
previousPoint2 = item.dataIndex;
$("#tooltip").remove();
var x = item.datapoint[0].toFixed(2),
y = item.datapoint[1].toFixed(2);
showChartTooltip(item.pageX, item.pageY, item.datapoint[0], '$' + item.datapoint[1]);
}
}
});
$('#site_revenue').bind("mouseleave", function () {
$("#tooltip").remove();
});
}
}
};
}();
jQuery(document).ready(function() {
Graphs.initCharts(); // init index page's custom scripts
});
JSFiddle: http://jsfiddle.net/fxc4vyg3/
You must be tired, you just have an off-by-one error, and you only called the update for the lines, not the points.
togglePlot = function(seriesIdx)
{
var previousPoint2 = plot_statistics.getData();
seriesIdx--; // ***HERE***
previousPoint2[seriesIdx].points.show = // ***AND HERE***
previousPoint2[seriesIdx].lines.show = !previousPoint2[seriesIdx].lines.show;
plot_statistics.setData(previousPoint2);
plot_statistics.draw();
}
Here's the fixed fiddle: http://jsfiddle.net/it_turns_out/fxc4vyg3/3/

The live graph stops when the mouse pointer is put inside the graph area?

The live graph stops when the mouse pointer is put inside the graph area. I need to have a live graph that displays values continuously irrespective of mouse movement.Please help me out.
The code is as follows.Please use " jsfiddle.net "
HTML:
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
JAVASCRIPT :
$(function () {
$(document).ready(function() {
Highcharts.setOptions({
global: {
useUTC: false
}
});
var chart;
$('#container').highcharts({
chart: {
type: 'areaspline',
animation: true, // don't animate in old IE
marginRight: 10,
events: {
load: function() {
// set up the updating of the chart each second
var seriesa = this.series[0];
var seriesb = this.series[1];
setInterval(function() {
var x1 = (new Date()).getTime(); // current time
var y1 = Math.random();
var x2 = (new Date()).getTime();
var y2 = Math.random();
seriesa.addPoint([x1, y1], true, true);
seriesb.addPoint([x2, y2], true, true);
}, 1000);
}
}
},
title: {
text: 'Live random data'
},
xAxis: {
title: {
text: 'Time'
},
tickWidth: 1 ,
// tickWidth: 2,
type: 'datetime',
labels:
{
enabled:false
},
tickColor: '#F00',
},
yAxis: {
title: {
text: 'speed'
},
labels: {
formatter: function()
{
if(this.value < 1000)
{
return this.value +'kbps';
}
else
{
var thisvalue = this.value;
thisvalue = thisvalue/1000;
thisvalue = thisvalue.toFixed(1);
return thisvalue +' mbps';
}
},
style:{
color: '#a6a6a6',
font: '10px Arial'
}
},
plotLines: [{
value: 50,
width: 1,
color: '#808080'
}]
},
tooltip: {//WE need shared tooltip
formatter: function() {
var s = '<br>'+ this.x +'</br>';
$.each(this.points, function(i, point) {
s += '<br/>'+ point.series[i].name +': '+
point.y +'<m>';
});
return s;
},
shared: true
},
legend: {
enabled: false
},
exporting: {
enabled: false
},
series: [{
name: 'download data',
color: '#037472',
lineWidth:2,
fillOpacity: 1,
fillColor:
{
linearGradient: [0, 0, 0, 180],
stops:
[
[0, 'rgba(123, 195, 194,1)'],
[1, 'rgba(123, 195, 194,0)'],
]
},
data: (function() {
// generate an array of random data
var data = [],
time = (new Date()).getTime(),
i;
for (i = -30; i <= 0; i++) {
data.push({
x: time + i * 1000,
y: Math.random()
});
}
return data;
})()
},
//2nd graph plotting
{
name: 'Upload Speed',
color: '#068cca',
lineWidth:2,
fillOpacity: 1,
fillColor: {
linearGradient: [0, 0, 0, 180],
stops:
[
[0, 'rgba(99, 204, 255,1)'],
[1, 'rgba(99, 204, 255,0)']
]
},
data:(function(){
// generate an array of random data
var data = [],
time = (new Date()).getTime(),
i;
for (i = -30; i <= 0; i++) {
data.push({
x: time + i * 1000,
y: Math.random()*3000
});
}
return data;
})()
}
]
}); //containers end highcharts ends
});
});
It doesn't work, because in the tooltip you referr to incorrect object, like point.series[i].name, which doesn't exist.

Categories

Resources