I am making one area graph dynamically in that I want to set the Data array dynamically. I have created variable and assign it Scores which example I have given below
$dataPoints = '30, 10, 40, 20, 30, 10, 50, 30, 30, 30, 40';
var dataPoints1 = '<?php echo $dataPoints; ?>';
var areaChart = c3.generate({
bindto: '#area-chart',
data: {
columns: [
['Score', dataPoints1]
],
types: {
data1: 'area',
Score: 'area-spline'
}
},
tooltip: {
show: true
},
legend: {
show: false
},
axis: {
x: {
show: false
},
y: {
show: false
},
},
grid:{
focus:{
show:false
}
}
});
But this Script is not working and it does not show a graph and if I set this value statically so it is working fine.
So can anybody help me with this...
Instead of fetching php string into js variable, pass php string directly to column, it will work
var areaChart = c3.generate({
bindto: '#area-chart',
data: {
columns: [
['Score', <?php echo $dataPoints; ?>] // use php variable directly
],
types: {
data1: 'area',
Score: 'area-spline'
}
},
tooltip: {
show: true
},
legend: {
show: false
},
axis: {
x: {
show: false
},
y: {
show: false
},
},
grid:{
focus:{
show:false
}
}
});
There is no need of dataPoints1 js variable.
EDIT
In that case,
In php I suppose ajax,
$dataPoints["Score"] = [30, 10, 40, 20, 30, 10, 50, 30, 30, 30, 40];
echo json_encode($dataPoints); die;
In JS
var chart = c3.generate({
bindto: '#area-chart',
data: {
url: 'your url to fetch above data',
mimeType: 'json',
types: {
data1: 'area',
Score: 'area-spline'
}
},
tooltip: {
show: true
},
legend: {
show: false
},
axis: {
x: {
show: false
},
y: {
show: false
},
},
grid: {
focus: {
show: false
}
}
});
This should solve your problem
I use your code as example and try to modify code with my database connection and sample table data.
Please try this, hope this will useful to you.
File (PHP + HTML + jQuery)
<?php
$servername = "localhost"; // Change with your server name
$username = "root"; // Change with your user name
$password = ""; // // Change with your password
$dbname = "test"; // // Change with your database name
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT data FROM users"; // // Change with your table name
$result = $conn->query($sql);
$dataPoints = '';
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$dataPoints .= $row['data'];
$dataPoints .= ',';
}
rtrim($dataPoints);
echo $dataPoints;
} else {
echo "0 results";
}
$conn->close();
?>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>C3.js</title>
<style type="text/css">
body{
text-align: center;
}
</style>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/c3/0.4.10/c3.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.16/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/c3/0.4.10/c3.min.js"></script>
</head>
<body>
<div class="container">
<h1>Graphs made easy</h1>
<div id="chart"></div>
</div>
<script type="text/javascript">
var dataPoints1 = ["Score", <?php echo $dataPoints;?>];
console.log('dataPoints : ', <?php echo $dataPoints;?>);
console.log('data2 : ', dataPoints1);
var areaChart = c3.generate({
bindto: '#chart',
data: {
columns: [
dataPoints1
],
types: {
data1: 'area',
Score: 'area-spline'
}
},
tooltip: {
show: true
},
legend: {
show: false
},
axis: {
x: {
show: false
},
y: {
show: false
},
},
grid:{
focus:{
show:false
}
}
});
</script>
</body>
</html>
Output
Related
Highchart scroll problem
When I scroll using the in built scroll bar of highcharts, some of the data is not being shown in the highcharts table, but when I scroll again, the data is shown and some other data is omitted out.
The code that I have used is given below for reference
code:-
<?php
$colorArray = ['#058DC7', '#50B432', '#ED561B', '#DDDF00', '#24CBE5', '#64E572', '#FF9655', '#FFF263', '#6AF9C4'];
$string ='[';
for($i=1;$i<=15;$i++){
$yearString = rand(2016,2018);
$monthString = rand(1,12);
$dateString = rand(1,28);
$endYearString = rand(2019,2021);
$string .= "{ start: Date.UTC($yearString, $monthString, $dateString),end: Date.UTC($endYearString, $monthString, $dateString),name: 'Initiative ".$i."',color: '".$colorArray[rand(0,8)]."', label:'Initiative ".$i."' },";
}
$string .= "{ start: Date.UTC(2020, 1, 1),end: Date.UTC(2021, 1, 12),name: 'Qus',color: '".$colorArray[rand(0,8)]."', label:'Qus' },";
$string .= "{ start: Date.UTC(2021, 1, 12),end: Date.UTC(2021, 1, 22),name: 'Qus',color: '".$colorArray[rand(0,8)]."', label:'Qus' },";
$string .= "{ start: Date.UTC(2021, 1, 23),end: Date.UTC(2021, 5, 31),name: 'Qus',color: '".$colorArray[rand(0,8)]."', label:'Qus' },";
for($i=1;$i<=30;$i++){
$yearString = rand(2016,2018);
$rnd = rand(1,5);
for($j=1;$j<$rnd;$j++){
$monthString = rand(1,12);
$dateString = rand(1,28);
$endMonthString = rand(1,12);
$endDateString = rand(1,28);
$endYearString = rand(2016,2021);
$string .= "{ start: Date.UTC($yearString, $monthString, $dateString),end: Date.UTC($endYearString, $endMonthString, $endDateString),name: 'Qus ".$i." - ".$j."',color: '".$colorArray[rand(0,8)]."', label:'Qus ".$i." - ".$j."' },";
}
}
$string .= "]";
// echo $string;die;
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="https://code.highcharts.com/gantt/highcharts-gantt.js"></script>
<script src="https://code.highcharts.com/stock/modules/exporting.js"></script>
<style>
#container {
max-width: 1200px;
margin: 1em auto;
}
</style>
</head>
<body>
<div id="container"></div>
<script>
Highcharts.setOptions({
colors: ['#058DC7', '#50B432', '#ED561B', '#DDDF00', '#24CBE5', '#64E572', '#FF9655', '#FFF263', '#6AF9C4']
});
Highcharts.ganttChart('container', {
chart: {
spacingLeft: 1,
style: {
fontFamily: ' Roboto, sans-serif;',
// fontWeigth: 'bolder'
}
},
title: {
text: 'Gantt Chart with Navigation'
},
yAxis: {
uniqueNames: true,
min: 0,
max: 7,
scrollbar:{
enabled : true
}
},
xAxis: {
currentDateIndicator: true,
type: 'category',
title: {
text: null
},
min: 0,
// max: 8,
scrollbar: {
enabled: true
},
tickLength: 0
},
tooltip: {
xDateFormat: '%a %b %d, %H:%M'
},
plotOptions:{
series: {
pointWidth: 13,
dataLabels: {
enabled: true,
format: '{point.label}',
style: {
cursor: 'default',
pointerEvents: 'none'
}
},
}
},
navigator: {
enabled: true,
series: {
type: 'gantt',
pointPlacement: 0.5,
pointPadding: 0.25
},
yAxis: {
min: 0,
max: 3,
reversed: true,
categories: []
}
},
scrollbar: {
enabled: true
},
rangeSelector: {
enabled: true,
selected: 5
},
series: [{
name: 'Project 1',
events:{
click: function(event){
console.log(event)
console.log(this)
alert("Clicked");
}
},
dataLabels: {
enabled: true,
style: {
textOutline: 0
}
},
data: <?php echo $string; ?>
}]
});
const callback = function(){
let text = document.querySelectorAll('.highcharts-data-label-color-undefined')
let box = document.querySelectorAll('.highcharts-partfill-original')
text.forEach((el,index)=>{
let child = el.children[0];
let boxWidth = box[index].getBoundingClientRect().width;
let textWidth = child.getBoundingClientRect().width;
// console.log(textWidth,boxWidth)
if (textWidth > boxWidth){
child.style.opacity = "0";
}else{
// child.textContent = z;
child.style.fill = "white";
child.style.opacity = "1";
}
})
};
callback();
window.addEventListener('resize', callback);
</script>
</body>
</html>
scrollbar:{
enabled : true
},
events: {
setExtremes: function(e){
let main = document.querySelector('.highcharts-plot-background').getBoundingClientRect();
const call = function(){
let bound = main.y + main.height;
let lines = document.querySelectorAll('.highcharts-tick')
let texts = document.querySelectorAll('.highcharts-treegrid-node-level-1');
texts.forEach(el=>{
let textlines = el.getBoundingClientRect();
if(textlines.y > main.y && textlines.y < bound-20){
el.style.visibility = "visible"
}else{
el.style.visibility = "hidden"
}
})
lines.forEach(el=>{
let pathlines = el.getBoundingClientRect();
let parent = el.parentNode
if(parent.classList.contains('highcharts-yaxis')){
if(pathlines.y > main.y && pathlines.y <bound){
el.style.visibility = "visible"
el.visibility = "visible"
}else{
el.style.visibility = "hidden"
el.visibility = "hidden"
}
}
})
}
setTimeout(function(){ call();},500)
}
}
},
I am following this example
https://www.highcharts.com/docs/chart-and-series-types/pie-chart
I want to display highcharts through retrieving data from the database. My pie highcharts is not displaying though I am not getting any error. I am retrieving data from database mysql. here is my code
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container2',
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: 'diseas Per area'
},
// tooltip: {
// formatter: function() {
// return '<b>' + this.point.name + '</b>: ' + this.y+ 'd Count';
// }
// },
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
color: '#000000',
connectorColor: '#000000',
formatter: function() {
return '<b>' + this.point.name + '</b>: ' + this.y;
}
},
showInLegend: true
}
},
series: []
};
$.getJSON("fcount.php", function(json) {
options.series = json;
chart = new Highcharts.Chart(options);
});
});
<div id="container2" style="height: 550px; min-width: 310px; max-width:800px; margin: 0 auto"></div>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
kindly tell me what I am doing wrong. It does not show any error but still it does not display
my php code is
<?php
$con=mysqli_connect("localhost","root","","test");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysql_query("SELECT `Area` AS Zone, COUNT( `Diease` ) AS problem FROM table GROUP BY `Area` ");
//$rows = array();
$rows['type'] = 'pie';
$rows['name'] = 'Diease Count';
//$rows['innerSize'] = '50%';
while ($r = mysql_fetch_array($result)) {
$rows['data'][] = array('zone '.$r['area'].'"', $r['problem']);
}
$rslt = array();
array_push($rslt,$rows);
print json_encode($rslt, JSON_NUMERIC_CHECK);
mysql_close($con);
instead of push array into an empty array like this
$rslt = array();
array_push($rslt,$rows);
print json_encode($rslt, JSON_NUMERIC_CHECK);
use it like below
echo json_encode($rows);
The lack of data is probably caused by the format of your options.series. When using a pie chart, your series should be formatted like this:
options.series = [{ name: 'Browsers',
data: [ ["Firefox",60] , ["Chrome",40]]
}]
In this JSFiddle I used your options code to generate the chart. So if your options.series looks like shown above, the chart should work.
I am getting temperature from MySQL DB and Now I want to plot graph for the same over last 3 days. But the graph doesnt get plotted .
Here is the code for two files.
//Sql.php
<?php
// if you want to send request from a html file stored
// locally uncomment the line below
header('Access-Control-Allow-Origin: *');
// in the commands "mysql_..." change the following:
// xxxx - your SQL server address (np: www.abc.com)
// yyyy - user name
// zzzz - password
// qqqq - database name
// watch out for the capital letters!
mysql_connect("192.168.100.107:3306", "root", "hannan786") or die(mysql_error());
mysql_select_db("pi") or die(mysql_error());
// describe the date ragne - here: the last 3 days
$phpdate=time()- (3*24 * 60 * 60);
$datefrom = date( 'Y-m-d H:i:s', $phpdate );
$dateto = date( 'Y-m-d H:i:s', time() );
$data = mysql_query("SELECT * FROM temp WHERE `time` > '$datefrom'
AND `time` < '$dateto' ORDER BY time ASC") or die(mysql_error());
$rowcount = mysql_num_rows($data);
$counter=1;
// prepare the answer needed by Highcharts:
echo '{
"title": {"text": "temperature"},
"chart": {"renderTo": "container"},
"series": [{"name": "temperature", "data":[';
// fill the data from the database,
// here - the data of interest is stored in column "Temp4":
while($r = mysql_fetch_assoc($data)) {
echo '['.strtotime($r["time"])*1000 . ', '.$r["temperature"]/10 .']';
if($counter < $rowcount){
echo ", ";
}
$counter=$counter+1;
}
// finalize the answer
echo' ]}]}';
mysql_free_result($data);
?>
And this is the another page , Which is index.html , where I want to plot the graph .
<!DOCTYPE HTML>
<html>
<head>
<html xmlns="http://www.w3c.org/1999/xhtml"; xml:lang="pl" lang="pl">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Hannan</title>
<!-- pliki js znajdziesz na www.jquery.com i www.highcharts.com-->
<script type="text/javascript" src="/js/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script type="text/javascript" src="js/highcharts.js"></script>
<script type="text/javascript" src="js/themes/grid.js"></script>
<script src="https://code.highcharts.com"></script>
<script type="text/javascript">
var options;
$(document).ready(function() {
Highcharts.setOptions({
global: {
useUTC: false
}
});
options = {
xAxis: {
type: 'datetime',
dateTimeLabelFormats: {
day: '%e of %b',
hour: '%H:%M<br>%d %b'
}
},
yAxis: [{
title: {
text: null
},
labels: {
align: 'left',
x: 3,
y: 16,
formatter: function() {
return Highcharts.numberFormat(this.value, 0);
}
},
showFirstLabel: false
}, {
linkedTo: 0,
gridLineWidth: 0,
opposite: true,
title: {
text: null
},
labels: {
align: 'right',
x: -3,
y: 16,
formatter: function() {
return Highcharts.numberFormat(this.value, 0);
}
},
showFirstLabel: false
}],
legend: {
align: 'left',
verticalAlign: 'top',
y: 0,
floating: true,
borderWidth: 0
},
tooltip: {
formatter: function() {
return Highcharts.dateFormat('%a, %d.%b %H:%M', this.x)+'<br><b>'+ this.series.name +' '+ this.y +'°C</b>';
}
},
plotOptions: {
series: {
cursor: 'pointer',
marker: {
enabled: false,
lineWidth: 1
}
}
}
};
$.getJSON("sql.php", function(json) {
var options1 = $.extend(json, options);
chart = new Highcharts.Chart(options1);
});
});
</script>
</head>
<body>
<div id="container" style="width: 800px; height: 400px; margin: 0 auto"></div>
</body>
</html>
The charts are using HighChart Library. Please help me out if you have any idea , Why the graph or chart isint working properly.
Thank You .
I had posted : passsing data to https by JSON using JSONP ,and tried to change the highchart by call back to JSONP but still I don't get any result. Could any one tell me what is the problem (perhaps I think the way, which I callback is wrong.)?
data.php:
<?php header("content-type: application/json");
$servername = "xxxxxx";
$username = "xxxxxx";
$password = "xxxxxx";
$dbname = "xxxxxx";
$con = mysql_connect($servername,$username,$password,$dbname);
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("xxxxxxxxxx", $con);
if (isset($_GET["dateparam"])) {
$sql = mysql_query("SELECT timestamp_value, User_Logins FROM foot_traffic WHERE timestamp_value LIKE '".$_GET["dateparam"]."%'");
} else {
$sql = mysql_query("SELECT timestamp_value, User_Logins FROM foot_traffic WHERE timestamp_value LIKE '2013-02-01%'");
}
$result['name'] = 'User_Logins over Time Period';
while($r = mysql_fetch_array($sql)) {
$datetime = $r['timestamp_value'];
$result['category'][] = $datetime;
$result['data'][] = $r['User_Logins'];
}
echo $_GET['callback']. '('. json_encode($result) . ')';
print json_encode($result, JSON_NUMERIC_CHECK);
mysql_close($con);
?>
file.php:
<html>
<head>
<script type="text/javascript">
var hey;
$(document).ready(function() {
hey = {
chart: {
renderTo: 'container1',
type: 'area',
borderColor: "#3366ff",
borderWidth:5,
zoomType : 'x'
},
title: {
text: 'All User_Logins of your All Organizations '
},
subtitle: {
text: ' '
},
credits:{
enabled:false
},
xAxis: {
categories: [],
labels: {
align: 'center',
x: -3,
y: 20,
formatter: function(){
return Highcharts.dateFormat('%l%p',Date.parse(this.value +' UTC'));
}
}
},
yAxis: {
title: {
text: ''
}
},
tooltip: {
backgroundColor: '#FCFFC5',
borderColor: 'black',
borderRadius: 10,
borderWidth: 3
},
// Enable for both axes
tooltip: {
borderWidth: 0,
backgroundColor: "rgba(255,255,255,0)",
borderRadius: 0,
shadow: false,
useHTML: true,
percentageDecimals: 2,
backgroundColor: "rgba(255,255,255,1)",
formatter: function () {
return '<div class="tooltip">' + this.point.name + '<br />' + '<b>' +
Highcharts.numberFormat(this.y).replace(",", " ") + ' Kč [' +
Highcharts.numberFormat(this.percentage, 2) + '%]</b></div>';
}
},
plotOptions: {
line: {
dataLabels: {
enabled: true
},
enableMouseTracking: false
}
},
series: [{
type: 'area',
name: '',
data: []
}]
}
$.getJSON("data.php?callback=?", function(json){
hey.xAxis.categories = json['category'];
hey.series[0].name = json['name'];
hey.series[0].data = json['data'];
chart = new Highcharts.Chart(hey);
});
});
$(function() {
$( "#datepicker" ).datepicker({
dateFormat: "yy-mm-dd",
showOn: "button",
buttonImage: "calendar.gif",
buttonImageOnly: true,
onSelect: function(dateText, inst) {
$.getJSON("data.php?dateparam?callback=?"+dateText, function(json){
hey.xAxis.categories = json['category'];
hey.series[0].name = json['name'];
hey.series[0].data = json['data'];
chart = new Highcharts.Chart(hey);
});
}
});
});
</script>
</head>
<body>
<!--date picker-->
<input type="text" id="datepicker" />
<!-- highchart container-->
<div id="container1" class="analysis" style=" margin: 0 auto">
</div>
</body>
</html>
My highcharts chart is showing like this now:
http://img90.imageshack.us/img90/3892/chart1p.png
But I need it to look like this:
http://img545.imageshack.us/img545/1333/chart2p.png
Currently its not showing empty values by hours.
My code:
index.php
<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 () {
var options = {
chart: {
renderTo: 'chart',
defaultSeriesType: 'spline'
},
title: {
text: 'Earnings Today',
},
subtitle: {
text: ''
},
xAxis: {
type: 'datetime',
tickInterval: 3600 * 1000,
tickWidth: 0,
labels: {
align: 'center',
formatter: function () {
return Highcharts.dateFormat('%l%p', this.value);
}
},
},
yAxis: {
title: {
text: 'Earnings'
},
min: 0,
tickInterval: 2,
},
plotOptions: {
spline: {
marker: {
radius: 4,
lineColor: '#666666',
lineWidth: 1
}
}
},
tooltip: {
valueDecimals: 2,
crosshairs: true,
formatter: function () {
return '$' + this.y;
}
},
series: [{
name: 'Earnings Today, USD'
}
]
}
jQuery.get('data_today.php', null, function (tsv) {
var lines = [];
earnings = [];
try {
tsv = tsv.split(/\n/g);
jQuery.each(tsv, function (i, line) {
line = line.split(/\t/);
date = Date.parse(line[0] + ' UTC');
val = line[1];
earnings.push([date, parseFloat(line[1].replace(',', '.'), 10)]);
});
} catch (e) {}
options.series[0].data = earnings;
chart = new Highcharts.Chart(options);
});
});
</script>
data_today.php
<?php
session_start();
require_once('config.php');
require_once('config_mysql.php');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!$link)
{
die('Failed to connect to server: ' . mysql_error());
}
$db = mysql_select_db(DB_DATABASE);
if (!$db)
{
die("Unable to select database");
}
$result = mysql_query("SELECT earn_date,SUM(amount) as val FROM user_earnings WHERE user_id='$USER_ID' AND DATE(earn_date) = DATE(NOW()) GROUP BY earn_date");
if ($result)
{
while ($row = mysql_fetch_array($result))
{
$d = date("l, F, j, Y G:i:s", strtotime($row["earn_date"]));
echo $d . "\t" . $row['val'] . "\n";
}
}
else
{
die(mysql_error());
}
mysql_close($link);
?>
So, (if its not enough clear yet) I need this code to show whole day and show also empty values by hour.
I have almost zero experience of highcharts and javascript, so I need some help with this :)
Also looking for alternative way for running MySql query inside index.php so I dont need data_today.php
Thanks
Set the xAxis as below
xAxis: {
ordinal: false
}
For empty spaces you should have null values. Then set connectNulls: false.
Example