I plot highcharts on my page.
This works great but i have one little problem that in my points when i hover with my mouse on it, i get no date and time with it.
This is what my json is like.:
[{"metingen":"metingen","Datum":"Datum","data":["5-9-2022",14.6,"5-9-2022",14.8,"6-9-2022",15.948,"6-9-2022",17.112,"6-9-2022",
My chart look then like this.:
You see on the left the baloon, it show the number 0: 14.6.
14.6 is the value, thats good but the 0 is number of that value sutch as another point, that gives
But how can i show the date and time thats belong with that number in the baloon?
My chart code is this.:
$.getJSON("mfrmetingen300RG.json", function(data) {
const processedData9 = [];
for (let a = 0; a < data[0].data.length; a += 2) {
processedData9.push([data[0].data[a], data[0].data[a + 1]]);
}
data[0].data = processedData9;
avg = <?php echo $rowj[0]; ?>;
StDev = <?php echo $rowj[1]; ?>;
Aantalwaarden9 = <?php echo $rowj[2]; ?>;
//Cp=(USL-LSL)/(6xstd.Dev) see.:https://www.easycalculation.com/statistics/learn-cp-cpk-calculator.php
//Cpk = (USL-gemiddelde) / (3 x std.Dev) of (gemiddelde-LSL) / (3 x std.Dev)
cpkl1 = (<?php echo $_cpkh10waarde; ?>-<?php echo $_cpkl10waarde; ?>)/(6*StDev);
Cpk1High = (<?php echo $_cpkh10waarde; ?>-avg)/(3*StDev);
Cpk1Low = (avg-<?php echo $_cpkl10waarde; ?>)/(3*StDev);
chart9 = new Highcharts.Chart('container9',{
chart: {
zoomType: 'x',
type: 'line',
marginRight: 130,
marginBottom: 100,
backgroundColor:'azure'
},
rangeSelector: {
buttons: [{
text: '+',
events: {
click() {
return false
}
}
},
{
text: '-',
events: {
click() {
return false
}
}
}]
},
title: {
useHTML: true,
text: "Gemeten MFR waarde van PP 300R Grey Extrusie over de laatste "+(Aantalwaarden9)+" waarden.",
x: -20 //center
},
credits: {
enabled: false
},
subtitle: {text: 'Gem.='+avg.toFixed(2)+' Stdev='+StDev.toFixed(2)+' Cp='+cpkl1.toFixed(2)+' Cpk_High='+Cpk1High.toFixed(2)+' Cpk_Low='+Cpk1Low.toFixed(2)+'',x: -20},
xAxis: {
uniqueNames: false,
type: 'category',
title: {
text: 'Datum'
}
},
yAxis: {
"min":15,
"max":23,
title: {
text: 'MFR'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}],
plotLines: [{value: <?php echo $_cpkl10waarde; ?>,color: <?php echo $_color_min_line; ?>,dashStyle: 'longdashdot',width: 2,label: {text: 'Minimum'}},
{value: <?php echo $_cpkh10waarde; ?>,color: <?php echo $_color_max_line; ?>,dashStyle: 'longdashdot',width: 2,label: {text: 'Maximum'}},
{value: <?php echo $_cpkm10waarde; ?>,color: <?php echo $_color_guide_line; ?>,dashStyle: 'shortdash',width: 2,label: {text: 'Richtlijn'}},
{value: avg.toFixed(2),color: <?php echo $_color_avg_line; ?>,dashStyle: 'spline',width: 2,label: {text: 'Avg'}},
]
},
tooltip: {
formatter: function() {
return '<b>Meetwaarden</b><br/>'+ this.x +': '+ this.y;
}
},
legend: {layout: 'vertical',align: 'right',verticalAlign: 'top', x: -100,y: 0,floating: true,borderWidth: 0},
series: data,
plotOptions: {
line: {
dataLabels: {
enabled: true
}
}
},
});
chart9.legend.allItems[0].update({name:'MFR'});
}, 1000);
});```
Because you have category type xAxis, your category name is contained in point.key variable. So, based on your example, you only need to refer to this.key
tooltip: {
formatter: function() {
return '<b>Meetwaarden</b><br/>'+ this.key +': '+ this.y;
}
},
Simplified Demo:
https://jsfiddle.net/BlackLabel/87bousnL/
API Reference:
https://api.highcharts.com/highcharts/tooltip.headerFormat
Related
I want to show values on graphs. i search alot but could not find my solution.
Here is the code below:
<script>
var ctx = document.getElementById("barChart");
ctx.height = 100;
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: <?php echo json_encode($Division); ?>,
datasets: [{
label: 'Target',
data: <?php echo json_encode($TARGET_QTY); ?>,
//backgroundColor: "rgba(255, 159, 64, 0.2)",
backgroundColor: "rgb(231, 123, 126)",
borderColor: "rgb(219, 219, 219)",
borderWidth: 1
},
{
label: 'Actual',
data: <?php echo json_encode($DISPATCH_QTY); ?>,
backgroundColor: "rgb(0, 191, 255)",
borderColor: "rgb(252, 252, 252)",
borderWidth: 1
}
]
},
options: {
responsive: true,
tooltips: {
"enabled": false
},
scales: {
yAxes: [{
gridLines: {
display:false,
},
ticks: {
beginAtZero:true
}
}]
},
title: {
display: true,
// position:"bottom",
text: 'Target vs Actual Dispatch'
},
hover: {
// Overrides the global setting
mode: 'label'
},
animation: {
duration: 1,
onComplete: function () {
var chartInstance = this.chart,
ctx = chartInstance.ctx;
ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontSize, Chart.defaults.global.defaultFontStyle, Chart.defaults.global.defaultFontFamily);
ctx.textAlign = 'center';
ctx.textBaseline = 'bottom';
this.data.datasets.forEach(function (dataset, i)
{
var meta = chartInstance.controller.getDatasetMeta(i);
meta.data.forEach(function (bar, index) {
var data = dataset.data[index];
ctx.fillText(data, bar._model.x, bar._model.y - 5);
});
});
}
},
/*legend: {
display: true,
// position : "bottom",
labels: {
fontColor: 'rgb(0, 0, 0)'
}
}*/
}
});
</script>
<div class="row">
<div class="col-md-12">
<div class="chart">
<canvas id="barChart" style="position: relative; height: 300px;"></canvas>
</div>
</div>
</div>
I search alot but could not show values in the bar graph. In this code value will be shown on the top of the graph but could not show on the bar. i want to show value on the bars of graph. either its a bar chart or pie chart. i use chart.js library. Please help me to get rid of this situation. Thanks in Advance.
I'm trying to display average grades for each individual assignment but I'm getting no luck displaying it within a Highchart Column. It displays just the legend and "where the graph should be".
I have my div <div id="container"></div> as well as the necessary SQL code:
$row=$db->prepare ("SELECT r.due_date as Due, m.module_name as Module, r.ass_name as Assignment, avg(amount) as Grade
from score s
INNER JOIN assignment r ON s.assignment_id = r.ass_id
INNER JOIN module m ON r.module_id = m.module_id
WHERE r.module_id = 7
GROUP BY r.due_date asc;");
<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 = {
chart: {
renderTo: 'container',
type: 'line',
marginRight: 130,
marginBottom: 25
},
title: {
text: 'Revenue vs. Overhead',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
categories: []
},
yAxis: {
title: {
text: 'Amount'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
this.x +': '+ this.y;
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
series: []
}
$.getJSON("avg_grades.json", function(json) {
options.xAxis.categories = json[0]['Assignments'];
options.series[0] = json[1];
chart = new Highcharts.Chart(options);
});
});
</script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<div id="container"></div>
<?php
$db=new PDO('mysql:dbname=attendance_database;host=localhost;','user','password');
$row=$db->prepare ("SELECT r.due_date as Due, m.module_name as Module, r.ass_name as Assignment, avg(amount) as Grade
from score s
INNER JOIN assignment r ON s.assignment_id = r.ass_id
INNER JOIN module m ON r.module_id = m.module_id
WHERE r.module_id = 7
GROUP BY r.due_date asc;");
$row2=$db->prepare ("SELECT r.due_date as Due, m.module_name as Module, r.ass_name as Assignment, avg(amount) as Grade
from score s
INNER JOIN assignment r ON s.assignment_id = r.ass_id
INNER JOIN module m ON r.module_id = m.module_id
WHERE r.module_id = 7
GROUP BY r.due_date asc;");
$row3=$db->prepare ("SELECT r.due_date as Due, m.module_name as Module, r.ass_name as Assignment, avg(amount) as Grade
from score s
INNER JOIN assignment r ON s.assignment_id = r.ass_id
INNER JOIN module m ON r.module_id = m.module_id
WHERE r.module_id = 7
GROUP BY r.due_date asc;");
$row->execute();
###############################
$json_data=array();
$json_data['name'] = 'Assignments';
foreach($row as $rec)
{
$json_data['value'][]=$rec['Assignment'];
}
##########################
$json_data2=array();
$json_data2['name'] = 'Grade';
$row2->execute();
foreach($row2 as $rec2)
{
$json_data2['value'][]=$rec2['Grade'];
}
$result = array();
array_push($result,$json_data);
array_push($result,$json_data2);
$fp = fopen("avg_grades.json", "w");
fwrite($fp, json_encode($result));
fclose($fp);
echo json_encode($result);
?>
Expected outcome
Highcharts.chart('container', {
chart: {
type: 'column'
},
title: {
text: 'Monthly Average Rainfall'
},
subtitle: {
text: 'Source: WorldClimate.com'
},
xAxis: {
categories: [
'Find Hidden Data',
'Google Hacking',
'Caine Testing',
'Penetration Testing',
'FA 2'
],
crosshair: true
},
yAxis: {
min: 0,
title: {
text: 'Grades %'
}
},
tooltip: {
headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
'<td style="padding:0"><b>{point.y:.1f} %</b></td></tr>',
footerFormat: '</table>',
shared: true,
useHTML: true
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: [{
name: 'Avg Grade',
data: [99, 70,80, 47.5, 70, 40]
}]
});
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
Actual outcome
Actual problem is in php $json_data2;
Instead of
$json_data2=array();
$json_data2['name'] = 'Grade';
$row2->execute();
foreach($row2 as $rec2)
{
$json_data2['value'][]=$rec2['Grade'];
}
it should be
$json_data2=array();
$json_data2['name'] = 'Grade';
$row2->execute();
foreach($row2 as $rec2)
{
$json_data2['value'][]=intval($rec2['Grade']); /*intval()*/
}
This will result in correct JSON string with array of numbers instead of array of string
final output [{"name":"Assignments","value":["Find Hidden Data","Google Hacking","Caine Testing","Penetration Testing","FA 2"]},{"name":"Grade","value":[99,70,80,47.5,70,40]}]
In your current JSON string,
this is demonstration to show when array of string ["99", "70","80", "47.5", "70", "40"] is converted to array of numbers [99, 70,80, 47.5, 70, 40] then only chart works as desired
var data = [{
"name": "Assignments",
"value": ["Find Hidden Data", "Google Hacking", "Caine Testing", "Penetration Testing", "FA 2"]
}, {
"name": "Grade",
"value": ["99", "70", "80", "47.5", "70", "40"]
}]
/*problem is here in second object value having array of string*/
var categories, datasN
for (var i = 0; i < data.length; i++) {
if (data[i].name == "Assignments") {
categories = data[i].value
}
if (data[i].name == "Grade") {
datasN = data[i].value.map(Number) /*converting string array to number array*/
}
}
Highcharts.chart('container', {
chart: {
type: 'column'
},
title: {
text: 'Monthly Average Rainfall'
},
subtitle: {
text: 'Source: WorldClimate.com'
},
xAxis: {
categories: categories,
crosshair: true
},
yAxis: {
min: 0,
title: {
text: 'Grades %'
}
},
tooltip: {
headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
'<td style="padding:0"><b>{point.y:.1f} %</b></td></tr>',
footerFormat: '</table>',
shared: true,
useHTML: true
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: [{
name: 'Avg Grade',
data: datasN
}]
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
Hope this gives you enough explanation
I am having a strange issue in jqplot bar chart. THe bar chart label in last bar is displaying sometimes and disappearing other times. I have added a screen shot and my script.!
Here is the script i have used.
plot1 = $.jqplot('chart1', [s1], {
// Only animate if we're not using excanvas (not in IE 7 or IE 8)..
animate: !$.jqplot.use_excanvas,
seriesColors:<?php echo json_encode($barColor ); ?>,
<?php if(isset($_POST['additionalSubmit'])){ ?>
negativeSeriesColors: ["#792A86"],
<?php } else { ?>
negativeSeriesColors: <?php echo json_encode($barColornegative ); ?>,
<?php } ?>
seriesDefaults:{
renderer:$.jqplot.BarRenderer,
rendererOptions: {
fillToZero: true,
barWidth: 30,
varyBarColor :true
},
pointLabels: {
show: true,
formatString :"€ %'s",
escapeHTML: false
}
},
canvasOverlay: {
show: true,
objects: [
{horizontalLine: {
name: 'zeroline',
y: 0,
lineWidth: 2,
xOffset: 0,
color: '#BBCCDD',
shadow: false
}}
]
},
axes: {
xaxis: {
autoscale:true,
renderer: $.jqplot.CategoryAxisRenderer,
ticks: ticks,
tickRenderer: $.jqplot.CanvasAxisTickRenderer,
tickOptions: {
fontSize: '8pt',
fontWeight: 'normal',
angle:-20,
},
borderColor: "#BBCCDD",
borderWidth:5
},
yaxis: {
autoscale:true,
tickOptions:{ prefix: '€' , formatString: "%'d",} ,
borderColor: "#BBCCDD",
borderWidth:5,
label: 'resultant in EURO',
labelRenderer: $.jqplot.CanvasAxisLabelRenderer
}
},
legend: {
show: true,
placement: 'outside',
noColumns: 1
},
series: [
{
fill: true,
label: '<?php echo $_POST['scenario']; ?>'
}
],
highlighter: { show: false }
});
Thanks in advance.
The labels will not show when they 'hit' the edges. To avoid this detection, set the edgeTolerance for your pointLabels like this:
pointLabels: {
show: true,
formatString :"€ %'s",
escapeHTML: false,
edgeTolerance: -100
}
I am using the Highcharts JavaScript library to visualize some float values, which i feed into the js code via php. As you can see in the following picture, on each point's mouseover are now displayed the two values that correspond to the axes values and the text "text: undefined".
My question is: Is there a way to display a different text for each point of the scatter plot? I have a text that corresponds to each point, but I haven't found a way to display it.
My JavaScript/php code is:
<script type="text/javascript">
$(function () {
var chart;
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'scatter',
zoomType: 'xy'},
title: {
text: 'Average 24hrs Sentiment for <?php echo $channel?> by Gender '
},
subtitle: {
text: 'Source: '
},
xAxis: {
title: {
enabled: true,
text: 'Hours ([0-24h].[0-60mins])'
},
startOnTick: true,
endOnTick: true,
showLastLabel: true
},
yAxis: {
title: {
text: 'Sentiment (N. Bayes) %'
}
},
tooltip: {
formatter: function() {
return ''+
this.x +' hrs, '+ this.y +' sentiment, text: ';
}
},
legend: {
layout: 'vertical',
align: 'left',
verticalAlign: 'top',
x: 24,
y: 1,
floating: true,
backgroundColor: '#FFFFFF',
borderWidth: 1
},
plotOptions: {
scatter: {
marker: {
radius: 5,
states: {
hover: {
enabled: true,
lineColor: 'rgb(100,100,100)'
}
}
},
states: {
hover: {
marker: {
enabled: false
}
}
}
}
},
series: [{
name: 'Female',
color: 'rgba(223, 83, 83, .5)',
data: [
<?php
for($j=0;$j<$i1;$j++)
{
if($females[$j]['Hour'][0] == "0")
{
echo '['.$females[$j]['Hour'][1].'.'.$females[$j]['Min'].','.$females[$j]['Sent'].'"]';
}
else
echo '['.$females[$j]['Hour'].'.'.$females[$j]['Min'].','.$females[$j]['Sent'].'"]';
if(($j+1)!=$i1)
{
echo ",";
}
}
?>
]},
{
name: 'Male',
color: 'rgba(119, 152, 191, .5)',
data: [
<?php
for($j=0;$j<$i2;$j++)
{
if($males[$j]['Hour'][0] == "0")
{
echo '['.$males[$j]['Hour'][1].'.'.$males[$j]['Min'].','.$males[$j]['Sent'].',"'.$males[$j]['Text'].'"]';
}
else
echo '['.$males[$j]['Hour'].'.'.$males[$j]['Min'].','.$males[$j]['Sent'].',"'.$males[$j]['Text'].'"]';
if(($j+1)!=$i2)
{
echo ",";
}
}
?>
]}]
});
});
});
Thank you.
If the text is unique to each point, you can pass more than the x and y as values. In the following example I pass three other values: locked, unlocked, and potential. Then to access them in the tooltip formatter, do so by using the this.point.locked
this.x +' hrs, '+ this.y +' sentiment, text: ';
Try to set the text in this code line,
just in order to check whether my suggestion will solve your problem,
try :
this.x +' hrs, '+ this.y +' sentiment, text: '+this.x;
And then check whether (this.x) value appears insted of "undefined" .
I have a table called "tracks",it looks like this:
id,
name,
url
hits
I have a pie charts, from highcharts, the code looks like this:
var chart;
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'chart',
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: 'Where users came from, total'
},
tooltip: {
formatter: function() {
return '<b>'+ this.point.name +'</b>: '+ this.percentage +' %';
}
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: false
},
showInLegend: true
}
},
credits: {
enabled: false
},
series: [{
type: 'pie',
name: 'Browser share',
data: [
['Firefox.com', 45.0],
['Default.com', 26.8],
['MSN', 12.8],
['Google.com', 8.5],
['Yahoo.com', 6.2],
['Others', 0.7]
]
}]
});
});
My question is, how can I get data from the "tracks" table (hits), and the (name) and output it in the pie chart like:
'name','hits'
And then, at last, convert # of hits, to %.
series: [{
type: 'pie',
name: 'Browser share',
data: [
<?php
$sql = 'select sum(hits) from tracks';
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
$totalHits = $row[0];
$sql = 'select name, hits from tracks order by hits desc';
$result = mysql_query($sql);
$i = 0;
$totalOther = 0;
$maxSlices = 5;
$minPercent = 10;
while ($row = mysql_fetch_row($result))
{
$percent = row[1] / $totalHits * 100;
if (++$i <= $maxSlices && $percent >= $minPercent)
{
echo json_encode($row);
}
else
{
$totalOther += $row[1];
}
}
if ( $totalOther > 0 ) echo json_encode(array('Other', $totalOther));
?>
]
}]
if you want to refresh it thourgh ajax...
...
series: [{
type: 'pie',
name: 'Browser share',
data: getData(function(result) {return result;}),
...
and
function getData(setDataCallback)
{
$.getJSON('file.php', args, function(result) { // use of jquery for clarity.
setDataCallback(result);
});
}
in php you have to do a new file ('file.php') with the code shown in the first code block;
Simplest way is to query data from mySql and then sort it same as
[
['Firefox.com', 45.0],
['Default.com', 26.8],
['MSN', 12.8],
['Google.com', 8.5],
['Yahoo.com', 6.2],
['Others', 0.7]
]
Requires if you want to show chart just on page loading.
You can also use JSON.