I get values to MySql database everyday at each hour.
I got site with highcharts, but I cant get it to work.
I need to get current day values from MySql organized to own hours.
Here is my Highcharts code:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script type="text/javascript">
var chart;
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'chart',
defaultSeriesType: 'spline'
},
title: {
text: "Today's Values"
},
subtitle: {
text: 'Values by Hour'
},
credits: {
enabled: false
},
xAxis: {
categories: ['12AM', '1AM', '2AM', '3AM', '4AM', '5AM',
'6AM', '7AM', '8AM', '9AM', '10AM', '11AM','12PM', '1PM', '2PM', '3PM', '4PM', '5PM',
'6PM', '7PM', '8PM', '9PM', '10PM', '11PM']
},
yAxis: {
min: 0,
title: {
text: 'Values'
},
labels: {
formatter: function() {
return this.value
}
}
},
tooltip: {
valueDecimals: 2,
crosshairs: true,
shared: true,
formatter: function() {
return '$' + this.y;
}
},
plotOptions: {
spline: {
marker: {
radius: 4,
lineColor: '#666666',
lineWidth: 1
}
}
},
series: [{
name: 'Values',
data: [
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
}]
});
});
</script>
Here is pic from MySql database how it looks like
chart
So, I need all values from MySql categorized to own hours at chart.
It should count values + show it at own category, any idea how to do this?
Im stuck with this beacause I dont know how to do this.
I advice to familiar with article about preprocessing data form MySQL http://docs.highcharts.com/#preprocessing-data-from-a-database
You should export your data from php as JSON, then if you would like you use categories for xAxis, you need to parse your JSON and push appropaite data to correct place.Similar with data points in series.
Related
So I've experienced some problems with one of my PHP pages using ChartJS, when I load my charts (Pie/Bar), with a good amount of data, then the google tab on revisit can not respond / say out of memory or something like that. I've read that it should be possible to make ChartJS be garbage-collected by calling .destroy(), but that removes my chart, so I don't know how that should be done?
Is there a proper way to create a chart, and then do some kind of clean-up after, and still show the chart on the webpage?
This is the function for barChart
**function barChart(barChartVal) {
const color = new chartColor();
new Chart(document.getElementById("chart-area-last-5-runs"), {
type: 'bar',
data: {
labels: [barChartVal[5][0], barChartVal[5][1], barChartVal[5][2], barChartVal[5][3], barChartVal[5][4]],
datasets: [{
data: [barChartVal[0][0], barChartVal[0][1], barChartVal[0][2], barChartVal[0][3], barChartVal[0][4]],
label: 'Passed',
backgroundColor: color.green(),
}, {
data: [barChartVal[1][0], barChartVal[1][1], barChartVal[1][2], barChartVal[1][3], barChartVal[1][4]],
label: 'Failed',
backgroundColor: color.red(),
}, {
data: [barChartVal[2][0], barChartVal[2][1], barChartVal[2][2], barChartVal[2][3], barChartVal[2][4]],
label: 'Error',
backgroundColor: color.yellow(),
}, {
data: [barChartVal[3][0], barChartVal[3][1], barChartVal[3][2], barChartVal[3][3], barChartVal[3][4]],
label: 'Not Run',
backgroundColor: color.blue(),
}, {
data: [barChartVal[4][0], barChartVal[4][1], barChartVal[4][2], barChartVal[4][3], barChartVal[4][4]],
label: 'Not Applicable',
backgroundColor: color.black(),
}]
},
options: {
scales: {
xAxes: [{
stacked: true,
ticks: {
display: false //this will remove only the label
}
}],
yAxes: [{ stacked: true }]
},
tooltips: {
/* tooltip text made smaller to longer labels fit */
mode: 'index',
intersect: false,
titleFontSize: 14,
bodyFontSize: 13,
bodySpacing: 0,
titleSpacing: 0,
xPadding: 2,
yPadding: 2,
cornerRadius: 2,
titleMarginBottom: 2
},
hover: {
mode: 'index',
intersect: false
},
animation: false, //No animations
parsing: false,
normalized: true
}
});
}**
Yes you can do something like that, you can transform the chart to an image and display that, then you can delete your chart which will free up the memory. Downside of this will be that its not interactable anymore:
const options = {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: 'orange'
},
{
label: '# of Points',
data: [7, 11, 5, 8, 3, 7],
backgroundColor: 'pink'
}
]
},
options: {
animation: false
}
}
const ctx = document.getElementById('chartJSContainer').getContext('2d');
const chartContainer = document.getElementById('chartJSContainer');
const chartImage = document.getElementById('chartImage');
const chart = new Chart(ctx, options);
const base64Chart = chart.toBase64Image();
// Set image source to chart image
chartImage.src = base64Chart;
// Destroy chart and remove canvas
chart.destroy();
chartContainer.remove();
<body>
<img id="chartImage">
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
</body>
I'm trying to hide the x-axis data label if no data is found. Please refer to the screenshot below. I want to show "0" or empty text instead of the date "01/01/1970".
How can I do that? My current code for flot chart is as below:
$.plot(elem, dataset1,
{
lines: { show: true, fill:true },
points: { show: true },
shadowSize: 0,
yaxis : {
show : true,
axisLabel : '<font style="color:#787878"><i>Total Views</i></font>',
position: 'left',
axisLabelPadding: 10,
tickDecimals: 0,
color: "#E0E0E0"
},
xaxis: {
mode: "time",
timeformat: "%d/%m/%Y",
minTickSize: [1, "day"],
color: "#E0E0E0",
axisLabel: '<font style="color:#787878">Date</font>',
axisLabelPadding: 20,
},
grid: {
hoverable: true,
borderWidth: 0
},
legend: { show: true, container: $('#legend-container'), noColumns: 1 },
tooltip: true,
tooltipOpts: {
content: function(label, xval, yval) {
var d = new Date(xval);
return label + ' (' + d.getDate() + '/' + (d.getMonth()+1) + '/' + d.getFullYear() +') : ' + yval
},
shifts: {
x: 20,
y: 0
},
defaultTheme: false
},
colors: [ "#4682B4" ]
}
You can add the following to the axis options to only show the axis if there are data points in your data set:
xaxis: {
show: dataset1.length > 0
...
I had a highcharts temperature gauge working when I put the javascript inline in my php file. However, I wanted to put the highcharts code in an "included" js file. Before, when I coded the javascript inline with the php file, it looked something like this:
// html and php above
// this inline code below works
<script>
$(document).ready(function(){
// here i simply accessed a php variable from
var $temperature_F = <?php echo round((($temp["Temperature"] * 9) / 5) + 32, 1); ?>;
var chart1 = new Highcharts.Chart({
// code initializing everything else in the highchart
series: [{
data: [{
id: 'temperature',
y: $temperature_F, // value taken from php variable
tooltip: {
valueSuffix: ' \xB0F'
}
}]
}]
});
})
</script>
// html and php below
Now, all I did was take this chunk of code, put it in a .js file and "include" it. I now just call a Print function from the php file, defined in my .js file, passing it the php variables I need. Like this:
<script type="text/javascript">
PrintTemperatureChart(1, '<?php echo $temperatureToDisplay; ?>', '<?php echo $dewPointToDisplay; ?>', '<?php echo $relativeHumidityToDisplay; ?>');
</script>
From within this function, I am able to "alert" out the expected php variables that I passed in, however, when I attempt to set "data:" to one of these variables, it breaks the chart. When I replace the variable with a dummy hard-coded value, it works. So I know just about everything else is set up correctly. Here's the function in the .js file:
function PrintTemperatureChart(unitsMode, temperature, dewPoint, relativeHumidity){
alert(unitsMode + ", " + temperature + ", " + dewPoint + ", " + relativeHumidity);
$(function () {
alert("The passed temperature = " + temperature);
var $theTemp = temperature;
var chart1 = new Highcharts.Chart({
chart: {
renderTo: 'Temperature_Chart',
type: 'gauge',
margin: 0
},
title: {
text: 'Temperature'
},
pane: {
startAngle: -150,
endAngle: 150,
background: [{
backgroundColor: {
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },
stops: [
[0, '#FFF'],
[1, '#333']
]
},
borderWidth: 0,
outerRadius: '109%'
}, {
backgroundColor: {
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },
stops: [
[0, '#333'],
[1, '#FFF']
]
},
borderWidth: 1,
outerRadius: '107%'
}, {
// default background
}, {
backgroundColor: '#DDD',
borderWidth: 0,
outerRadius: '105%',
innerRadius: '103%'
}]
},
yAxis: {
title: {
text: '\xB0F'
},
min: 0,
max: 120,
minorTickInterval: 1,
minorTickWidth: 1,
minorTickLength: 5,
minorTickPosition: 'inside',
minorGridLineWidth: 0,
minorTickColor: 'black',
tickInterval: 10,
tickWidth: 2,
tickPosition: 'inside',
tickLength: 10,
tickColor: 'black',
},
series: [{
name: 'Temperature',
data: [$theTemp], // this doesn't work
// this is the js var set to the passed in temperature
// I've also just tried using the param directly
// only a hard coded value will work
// i.e. data: [56],
tooltip: {
valueSuffix: ' \xB0F'
}
}]
});
});
}
I just need to use these variables passed in as data in my chart. Thanks in advance!
By placing single quotes around the PHP code like this:
PrintTemperatureChart(1, '<?php echo $temperatureToDisplay; ?>');
these variables were being passed as strings, which is incompatible with the integer type the "data" field expects in HighCharts. Solution:
PrintTemperatureChart(1, <?php echo $temperatureToDisplay; ?>);
I'm trying to display data from MSSQL. I saw an example at http://www.blueflame-software.com/blog/using-highcharts-with-php-and-mysql.
Value of Y Axis already good, but the X axis cannot display on my chart, so the value of chart only in 0 Xaxis,
data.php
mssql_select_db("CU-CAB01", $con);
$result = mssql_query("select count(nba) sumnba, datein from tbl_anggota where tgl_masuk > '2012-06-01'group by tgl_masuk");
while($row = mssql_fetch_array($result)) {
echo $row['tgl_masuk'] . "\t" . $row['jumlah']. "\n";
index.php
<script type="text/javascript" src="js/jquery-1.7.1.min.js" ></script>
<script type="text/javascript" src="js/highcharts.js" ></script>
<script type="text/javascript" src="js/themes/dark-blue.js"></script>
<script type="text/javascript">
var chart;
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
defaultSeriesType: 'line',
marginRight: 130,
marginBottom: 25
},
title: {
text: 'Hourly Visits',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
type: 'datetime',
tickInterval: 10000 * 1000, // one hour
tickWidth: 0,
gridLineWidth: 1,
labels: {
align: 'center',
x: -3,
y: 20,
formatter: function() {
return Highcharts.dateFormat('%e', this.value);
}
}
},
yAxis: {
tickInterval: 2,
title: {
text: 'Anggota'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return Highcharts.dateFormat('%l%p', this.x-(1000*3600)) +'-'+ Highcharts.dateFormat('%l%p', this.x) +': <b>'+ this.y + '</b>';
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
series: [{
name: 'Count'
}]
}
jQuery.get('data.php', null, function(tsv) {
var lines = [];
traffic = [];
try {
// split the data return into lines and parse them
tsv = tsv.split(/\n/g);
jQuery.each(tsv, function(i, line) {
line = line.split(/\t/);
date = Date.parse(line[0] +' UTC');
traffic.push([
date,
parseInt(line[1].replace(',', ''),10)
]);
});
} catch (e) { }
options.series[0].data = traffic;
chart = new Highcharts.Chart(options);
});
});
</script>
and my data in tbl_anggota query result like this
sumnba datein
1 2012-07-03 00:00:00.000
4 2012-07-04 00:00:00.000
5 2012-07-05 00:00:00.000
5 2012-07-06 00:00:00.000
2 2012-07-16 00:00:00.000
5 2012-07-17 00:00:00.000
1 2012-07-18 00:00:00.000
2 2012-07-19 00:00:00.000
I think my mistake in parsing data with jquery on datein field, so my Xaxis only in null value..
Can someone get my chart to display the Xaxis value?
If you output query is like above, you have your X and Ys reversed in your parsing. The date field is after the count field:
// split the data return into lines and parse them
tsv = tsv.split(/\n/g);
jQuery.each(tsv, function(i, line) {
line = line.split(/\t/);
date = Date.parse(line[1] +' UTC'); //your datin is after the '\t'
traffic.push([
date,
parseInt(line[0].replace(',', ''),10) //your count is before the '\t'
]);
});
And please, please fix the empty catch block. Ignore errors in a critical section of code is never a good idea.
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" .