Highcharts gradient fill how to? - php

I read a Json file to compile my highchart graph, but I want to have a nice gradient under the lines, Something like we see here.
Highcharts Area chart gradient fill
I've tried already some options and had already a search in the highcharts, but I haven't find anything useable.
Any ideas?
Thanks!
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highcharts Example</title>
<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: 'spline',
marginRight: 100,
marginBottom: 60
},
title: {
text: 'Temperature / Humidity / CPU',
x: -20 //center
},
subtitle: {
text: 'Overview 24u',
x: -20
},
xAxis: {
categories: []
},
yAxis: {
title: {
text: ''
},
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
this.x +': <b>'+ this.y +'</b>';
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: 0,
y: 50,
borderWidth: 0
},
series: []
}
$.getJSON("data.php", function(json) {
options.xAxis.categories = json[0]['data'];
options.series[0] = json[1];
options.series[0].color = '#e2432b';
options.series[0].lineWidth = 4;
options.series[1] = json[2];
options.series[1].color = '#c4faff';
options.series[2] = json[3];
options.series[2].color = '#b0ffaa';
options.series[2].linearGradient = 'x1:0,x2:0,y1:0,y2:1';
options.series[2].stops = '0, #b0ffaa', '1, #554488';
options.series[2].lineWidth = 2;
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>
</head>
<body>
<div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div>
</body>
</html>
Changed code, see comments below. But no gradient :(
...
options.series[1] = json[2];
options.series[2] = json[3];
options.series[2].fillColor = {
linearGradient: {
x1: 0,
y1: 0,
x2: 0,
y2: 1
},
stops: [
[0, '#000000'],
[1, '#333333']
]
};
options.series[2].lineWidth = 2;
chart = new Highcharts.Chart(options);
...

It's a problem with liner gradient definition, it should be:
series[2].fillColor = {
linearGradient: {
x1: 0,
x2: 0,
y1: 0,
y2: 1
},
stops: [
[0, '#b0ffaa'],
[1, '#554488']
]
};

Related

Unable to load Chart.js data from getJSON / PHP?

I am trying to add chart data from PHP file.
Chart is drawn when I add the values manually - data: [28,20,2,7],
But chart doesn't appear, when I add the data from PHP file.
Where am I going wrong here?
How can I add these values from PHP output?
My PHP code:
echo json_encode(array($rectotals,$recX,$recXS,$recXM));
Php file output (this looks OK):
[28,20,2,7]
Here is how i get the data:
$.getJSON("chartdata.php").then(function(chart_data1){
alert(chart_data1);
})
Alert result (This is also OK):
localhost:63342 says 28,20,2,7
My chartjs script:
<canvas id="myChart" width="400" height="340"></canvas>
<script>
$.getJSON("chartdata.php").then(function(chart_data){
alert(chart_data);
})
//setTimeout(function() { alert(db_data1); }, 2000);
var ctx = document.getElementById('myChart');
var myChart = new Chart(ctx, {
type: 'pie',
data: {
labels: ['Total', 'Size X', 'Size XS', 'Size SM],
datasets: [{
data: chart_data,
backgroundColor: [
'rgba(54, 162, 235, 1)',
'rgb(255,99,132)',
'rgba(255, 159, 64, 1)',
'rgb(255,206,86)'
],
borderColor: [
'rgba(54, 162, 235, 1)',
'rgba(255, 99, 132, 1)',
'rgb(255,159,64)',
'rgba(255, 206, 86, 1)'
],
borderWidth: 0.5,
}]
},
options: {
responsive: true,
animation: {
duration: 2800,
easing: 'easeInOutQuad',
},
layout: {
padding: {
left: 0,
right: 0,
top: 15,
bottom: 0
}
},
cutoutPercentage : 75,
legend: {
display: false,
position: 'bottom',
fullWidth: true,
}
}
});
</script>
var ctx = document.getElementById("myChart").getContext("2d");
let myChart = null;
function getConfig(chart_data){
return ({
type: "pie",
data: {
labels: ["Total", "Size X", "Size XS", "Size SM"],
datasets: [
{
data: chart_data,
backgroundColor: [
"rgb(54,162,235)",
"rgb(255,99,132)",
"rgba(255, 159, 64, 1)",
"rgb(255,192,33)"
],
borderColor: [
"rgb(255,255,255)",
"rgb(255,255,255)",
"rgb(255,255,255)",
"rgb(255,255,255)"
],
hoverBackgroundColor: ['#373739', '#373739', '#373739', '#373739'],
}
]
},
options: {
responsive: true,
animation: {
duration: 0, //2800, I remove animation time
easing: "easeInOutQuad"
},
tooltips: {
mode: 'nearest'
},
layout: {
padding: {
left: 0,
right: 0,
top: 15,
bottom: 0
}
},
cutoutPercentage: 66,
legend: {
display: false,
position: "bottom",
fullWidth: true
}
}
});
}
function getJSON(){
// emulate fetch
return new Promise(resolve => {
const chart_data = [
Math.random() * 50,
Math.random() * 50,
Math.random() * 50,
Math.random() * 50
];
resolve(chart_data)
})
}
function update(){
getJSON().then(data => {
myChart.data.datasets[0].data = data;
myChart.update();
});
}
function initializeChart() {
getJSON().then(data => {
myChart = new Chart(ctx, getConfig(data));
});
}
initializeChart();
document.getElementById('update_chart').addEventListener('click', update, false);
<html>
<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<div>
<button id="update_chart">Update Records</button>
</div>
<canvas id="myChart" width="50" height="40"></canvas>
</body>
</html>
Query.getJSON() makes an asynchronous HTTP request. Once the result arrives, the chart has already been created and the obtained data has no effect on the chart.
To solve this, place the chart creation inside the then callback as follows.
$.getJSON("chartdata.php").then(function(chart_data) {
var ctx = document.getElementById('myChart');
var myChart = new Chart(ctx, {
type: 'pie',
...
});

How to show values on pie or bar graph chart in php using chart.js

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.

How to avoid Y axis negative values from google charts

How to avoid the negative values from google chart, I tried viewWindow: { min: 0,} in my Y axis, but still it showing negative values only.
please help some one please. Thanks in advance
<div class="timeline-item">
<div id="top_x_div" style="width: 100%; height: 300px;"></div>
</div>
<script type="text/javascript">
google.charts.load('current', {packages: ['corechart', 'bar']});
google.charts.setOnLoadCallback(drawStacked);
function drawStacked() {
var data = new google.visualization.arrayToDataTable([
['Courses', 'Students'],
["Electronics", 2 ],
]);
var options = {
legend: { position: 'none' },
isStacked: true,
colors: ['green'],
bars: 'vertical', // Required for Material Bar Charts.
axes: {
x: {
0: { side: 'bottom', label: 'Percentage'} // Top x-axis.
}
},
axes: {
y: {
0: { side: 'bottom', label: 'Students'}, // Top x-axis.
/* viewWindow: {
min: 0,
},*/
}
},
vAxis: {
viewWindow: {
min: 0
}
},
bar: { groupWidth: "90%" }
};
var chart = new google.charts.Bar(document.getElementById('top_x_div'));
chart.draw(data, options);
};
</script>
You need to set the viewWindow on the vAxis option.
vAxis: {
viewWindow: {
min: 0
}
}
Source

highcharts not displaying graph

im trying to print results stored in my database using php and highcharts api.but the graph doesnt show on the screen.not even the axis get displayed.the data is got from a mysql database.i tries using the same code as in the highcharts demo but no luck.heres my code
<?php
require_once ('connection.php');
session_start();
$username = $_SESSION['username'];
$quizes=null;
$score=array();
$i=0;
$result = mysql_query("SELECT * FROM `score` WHERE `username`='$username'") or die(mysql_error);
while($rows=mysql_fetch_array($result)) {
$quizes= $quizes. "'".$rows['quiz']."',";
$score[$i]=$rows['score'];
$i=$i+1;
}
print_r($score);
echo $quizes;
?>
<html>
<body>
<script src="js/jquery.js"></script>
<script src="highcharts/js/highcharts.js"></script>
<script type="text/javascript">
$(document).ready(function() {
//passing php variables to javascript variables
//eg var mk1=<?php echo $mark1 ?>;
var mk1=<?php echo $score[1] ?>;
var mk2=<?php echo $score[2] ?>;
var mk3=<?php echo $score[3] ?>;
var mk4=<?php echo $score[4] ?>;
var mk5=<?php echo $score[5] ?>;
var mk6=<?php echo $score[6] ?>;
var mk7=<?php echo $score[7] ?>;
var mk8=<?php echo $score[8] ?>;
var chart1 = new Highcharts.Chart({
chart: {
renderTo: 'graphDiv',
defaultSeriesType: 'column'
},
title: {
text: 'SEMESTER'
},
xAxis: {
categories: ['QUIZ A', 'QUIZ B', 'QUIZ C', 'QUIZ D', 'QUIZ E', 'QUIZ F','QUIZ G','QUIZ H']
},
yAxis: {
title: {
text: 'Percentage'
}
},
series: [{
name: ['Quiz Progress'],
data: [mk1, mk2, mk3, mk4, mk5, mk6, mk7, mk8]
},]
});
});
</script>
<div id="graphDiv" style="width: 700px; height: 400px; float: left"></div>
</body>
</html>
Here is example to get data from mysql database in highchart.
Lest start with
Index.php
<head>
<meta name="Gopal Joshi" content="Highchart with Mysql" />
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Highchart with Mysql Database</title>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/setup.js"></script>
<script type="text/javascript" src="js/test.js"></script>
</head>
<body>
<script src="js/highcharts.js"></script>
<div id="sales" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
</body>
setup.js
var chart;
$(document).ready(function() {
var cursan = {
chart: {
renderTo: 'sales',
defaultSeriesType: 'area',
marginRight: 10,
marginBottom: 20
},
title: {
text: 'Highchart With Mysql',
},
subtitle: {
text: 'www.spjoshis.blogspot.com',
},
xAxis: {
categories: ['Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', 'Jan', 'Feb', 'Mar']
},
yAxis: {
title: {
text: 'Average'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
crosshairs: true,
shared: true
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 30,
borderWidth: 0
},
plotOptions: {
series: {
cursor: 'pointer',
marker: {
lineWidth: 1
}
}
},
series: [{
color: Highcharts.getOptions().colors[2],
name: 'Test Colomn',
marker: {
fillColor: '#FFFFFF',
lineWidth: 3,
lineColor: null // inherit from series
},
dataLabels: {
enabled: true,
rotation: 0,
color: '#666666',
align: 'top',
x: -10,
y: -10,
style: {
fontSize: '9px',
fontFamily: 'Verdana, sans-serif',
textShadow: '0 0 0px black'
}
}
}],
}
//Fetch MySql Records
jQuery.get('js/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 = line[0] ;
amo=parseFloat(line[1].replace(',', ''));
if (isNaN(amo)) {
amo = null;
}
traffic.push([
date,
amo
]);
});
} catch (e) { }
cursan.series[0].data = traffic;
chart = new Highcharts.Chart(cursan);
});
});
Here js will import data from mysql using data.php file and supply it to our chart
data.php
$con=mysql_connect('localhost','root','');
mysql_select_db("test", $con);
$result=mysql_query('select * from sales order by id');
while($row = mysql_fetch_array($result)) {
echo $row['month'] . "\t" . $row['amount']. "\n";
}
data.php will simply print value on page that we will use for chart.
You can use this method with multiple charts on same page and no more files will required for more then single chart.
It will output like
Click Here for more help or Download example.
I think your getting data in string format. convert data to integer like this way,
var mk1=<?php echo $score[1] ?>;
to integer: +mk1 // and check typeof +mk1
Here is the demo http://jsfiddle.net/XF293/
I advice to consider use json_encode() in php and return all values as single array. Then use $.getJSON() to avoid problems with printing values. As a result how your data looks like? I mean in javascript.

Multiple series, multiple charts Highcharts

i have to create a single chart showing different series with different type of chart (Ex: one data series with 'areaspline' and one data series with 'column'). I built a db with a lot of data, extracted by sql query into a json file
[
{ "name": "Test", "data": [2.8,2.8,2.8,2.7,2.7,] },
{ "name": "kwc", "data": [10,1,10,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] }
]
The json file is correct, but if i try to select the series for a chart with the $.each function it doesn't work!
Here's my code
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highcharts Example</title>
<script src="estrazione.php"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$.getJSON("new3.php", function(json) {
$.each(json.data, function(index, item){
// split the data set into ohlc and volume
var temperatura = [],
misura = [],
dataLength = json.length;
for (i = 0; i < dataLength; i++) {
temperatura.push([
data[i][0]
]);
misura.push([
data[i][1]
])
}
$('#container').highcharts({
chart: {
zoomType: 'xy'
},
title: {
text: 'Analisi Temperature e Consumo Generale',
},
xAxis: [{
categories: ['00.00', '00.15', '00.30', '00.45', '01.00', '01.15', '01.30', '01.45', '02.00', '02.15', '02.30', '02.45', '03.00', '03.15', '03.30', '03.45', '04.00', '04.15', '04.30', '04.45', '05.00', '05.15', '05.30', '05.45', '06.00', '06.15', '06.30', '06.45', '07.00', '07.15', '07.30', '07.45', '08.00', '08.15', '08.30', '08.45', '09.00', '09.15', '09.30', '09.45', '10.00', '10.15', '10.30', '10.45', '11.00', '11.15', '11.30', '11.45', '12.00', '12.15', '12.30', '12.45', '13.00', '13.15', '13.30', '13.45', '14.00', '14.15', '14.30', '14.45', '15.00', '15.15', '15.30', '15.45', '16.00', '16.15', '16.30', '16.45', '17.00', '17.15', '17.30', '17.45', '18.00', '18.15', '18.30', '18.45', '19.00', '19.15', '19.30', '19.45', '20.00', '20.15', '20.30', '20.45', '21.00', '21.15', '21.30', '21.45', '22.00', '22.15', '22.30', '22.45', '23.00', '23.15', '23.30', '23.45'],
}],
yAxis: [{ // Primary yAxis
labels: {
format: '{value}°C',
style: {
color: '#89A54E'
}
},
title: {
text: 'Temperature',
style: {
color: '#89A54E'
}
}
}, { // Secondary yAxis
title: {
text: 'Consumo',
style: {
color: '#4572A7'
}
},
labels: {
format: '{value} Kw',
style: {
color: '#4572A7'
}
},
opposite: true
}],
tooltip: {
shared: true
},
legend: {
layout: 'vertical',
align: 'left',
x: 120,
verticalAlign: 'top',
y: 100,
floating: true,
backgroundColor: '#FFFFFF'
},
series: [{
name: 'Misure',
color: '#4572A7',
type: 'column',
yAxis: 1,
data: misura,
tooltip: {
valueSuffix: ' Kw'
}
}, {
name: 'Temperature',
color: '#89A54E',
type: 'spline',
data: temperatura,
tooltip: {
valueSuffix: '°C'
}
}]
});
});
</script>
</head>
<body>
<script src="js/highcharts.js"></script>
<script src="js/modules/exporting.js"></script>
<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
</body>
</html>'
this is my php code:
<?php
$data_scelta = "2013-08-08";
$misura = "kwc";
$temperatura = "Test";
$link = mysqli_connect('localhost:3306', 'root', '','telegestione');
if (!$link) {
die('Could not connect: ' . mysqli_error());}
$sth = mysqli_query($link,"SELECT $temperatura FROM temperature WHERE dataora BETWEEN '$data_scelta 00:00:00.000'
AND '$data_scelta 23:59:59.997'");
$rows = array();
$rows['name'] = $temperatura;
while($r = mysqli_fetch_assoc($sth)) {
$rows['data'][] = $r[$temperatura];}
$sth = mysqli_query($link,"SELECT $misura FROM misure WHERE dataora BETWEEN '$data_scelta 00:00:00.000'
AND '$data_scelta 23:59:59.997'");
$rows1 = array();
$rows1['name'] = $misura;
while($rr = mysqli_fetch_assoc($sth)) {
$rows1['data'][] = $rr[$misura];}
$result = array();
array_push($result,$rows);
array_push($result,$rows1);
print json_encode($result, JSON_NUMERIC_CHECK);
?>
I tryed any kind of option, but anything gone right :(
Any hope to display 1 chart, 2 or more data series and 2 or more type of charts?
Thanks in advance
It looks like your highcharts creation call is within your $.each function. So it will try to create 2 highcharts, but they both will be created in the same div, so you'll only end up with one.
Also, the way you are caculating datalength, it'll be 2. When, it appears, you'd like it to be the length of the actual data (which is different for your different series).
I can't do the getJSON in a jsfiddle, so I'm assuming your PHP code is creating the json object you listed (and it looks like it would). You can lose the each loop alltogether and set your 2 series like this:
series: [{
name: 'Misure',
color: '#4572A7',
type: 'column',
yAxis: 1,
data: json[1].data,
tooltip: {
valueSuffix: ' Kw'
}
}, {
name: 'Temperature',
color: '#89A54E',
type: 'spline',
data: json[0].data,
tooltip: {
valueSuffix: '°C'
}
}]
http://jsfiddle.net/bhlaird/dUkuY/

Categories