3d interactive pie chart offline - javascript

I want to constract a 3d interactive pie chart. Firstly I use google charts but unfortunately this doesn't work offline. I used charts from jpgraph, jscharts and rgraph but doesn't have the effect that I want. I want a graph which must be free, work offline and has approximately the same appearance with google graph. Any advice?
Thanks in advance!
Important I want to use results from my db. I write this code but dont work:
data: [{
name: 'Present',
y: <?php
while( $row2 = mysql_fetch_assoc($res2)){
echo $row2["COUNT(*)"];
}
}, {
name: 'absentees',
y: <?php
while( $row1 = mysql_fetch_assoc($res1)){
echo $row1["COUNT(*)"];
}
I have those queries:
SELECT COUNT(*)
FROM staff s, work w, absence a
WHERE s.id=a.id_staff
AND s.id_work=w.id
AND w.name='sales manager'
AND a.name='disease'
SELECT COUNT(*)
FROM staff s, work w, absence a
WHERE s.id=a.id_staff
AND s.id_work=w.id
AND w.name='sales manager'
AND a.name='vacation'
I try this but doesnt work
series: [{
type: 'pie',
name: 'Absent',
data: [
['Absent Illness', <?php
while( $row1 = mysql_fetch_assoc($res1)){
while( $row2 = mysql_fetch_assoc($res2)){
$row['COUNT(*)']=$row2['COUNT(*)'] - $row1['COUNT(*)'];
echo $row["COUNT(*)"];
}
}
?>],
['Absent Vacation',
<?php
while( $row1 = mysql_fetch_assoc($res1)){
echo $row1["COUNT(*)"];
}
?>]
]
}]
});

Please use highchart because it provide the varrious type of charts and you can also use it offline mode also. https://www.highcharts.com/

Let me guide to display mysql results onto the pie chart.
function functionname() {
$.ajax({
url : 'POST API LINK',
type : 'GET',
dataType : 'json',
success : function(data) {
var chart = new CanvasJS.Chart("chartContainer", {
title : {
text : "A suitable title"
},
animationEnabled : true,
zoomEnabled : false,
data : [ {
type : "pie",
dataPoints : [ {
y : data.active,
indexLabel : "Active part=" + data.active
}, {
y : data.Inactive,
indexLabel : "Inactive part=" + data.Inactive
},
]
} ]
});
chart.render();
},
error : function() {
alert('sorry!Somthing went wrong in Pie chart');
}
});
}
This is how you display MySQL results.
Here In data,I am getting active and inactive value from my DB.
For the UI, Please check this fiddle link.
Kindly let me know if you have any queries.

Related

How to properly display data in chartjs from SQL?

I got started with chartJS, so I really need guidance of where to look and learn. I'm trying to display duplicated data from my SQL to chartJS.
Example:
Table name: Traffic Violations
Data I want to display: Violation types (Speeding, drifting, seatbelt, etc).
How it should be displayed: Y-axis as numbers, X-axis as violation names.
I read this: SQL count how many duplicated values of a derived table
Watched this: 1.3: Graphing with Chart.js - Working With Data & APIs in JavaScript
also watched this: How to Switch Chart to Daily, Weekly and Monthly Data in Chart js
And this: Count Total number of rows in database in php -Analytics in php
I learned few things from each, but still didn't satisfy my knowledge needs to achieve the goal I want.
I want to display the data in "Daily", "Monthly", "Yearly" format.
Sounds like that's a totally different topic, because I want the "daily" chart to reset every 24 hours, and monthly every month without deleting the data from DB. None of these videos above shows me that, nor I couldn't find what I'm looking for..
So, how to prepare my DB for chartJS?
best practice to fetch data and show it in the chart?
Here is what I have so far:
<?php
header('Content-Type: application/json');
require_once('./backend/config/connection.php');
$sqlQuery = "SELECT violationType, count(*) AS duplicates FROM traffic_violations GROUP BY violationType ORDER BY duplicates DESC";
$statement = $connection->prepare($sqlQuery);
$statement->execute();
$result = $statement->fetchAll();
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
if ($row->num_rows > 0)
{
// output data of each row
while($row = $row->fetch_assoc())
{
echo $row["duplicates"]. "<br>";
}
}
else
{
}
echo json_encode($data);
?>
Chart:
const ctx = document.getElementById('chart-test').getContext('2d');
const myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Speeding', 'Drifting', 'Sealtbelt', 'Wrong Parking', 'Wrong Lane Drive', 'No License'],
datasets: [{
label: 'Traffic Violations',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: ['rgba(255, 99, 132)'],
borderColor: ['rgba(255, 99, 132)'],
borderWidth: 1
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});

Using PHP and Javascript in a hybrid way, to traverse through a loop

I am trying to draw two graphs using chartjs. I want to make my life simplier by using a for loop to declare the variables required for the chart object.
The thing is I have created a 2d array, with each row storing data for current year, the next row storing data for the consecutive year and so on. I am trying to access the row of the variable using loop.
Here is my Chart obj
var canvas6= {
type: 'doughnut',
data: {
datasets: [{
data: [
<?php
for($i=0;$i<count($dataAgeGrp[1]);$i++){ -------->Note here
echo $dataAgeGrp[1][$i]; -------->And here
echo ',';
}
?>
],
backgroundColor: [
<?php
for($i=0;$i<count($ageCategory);$i++){
$rand = str_pad(dechex(rand(0, 0xFFFF00)), 6, 0, STR_PAD_LEFT);
echo('"#' . $rand.'"');
echo ",";
}
?>
],
label: 'Pie Chart'
}],
labels: [
<?php
for($i=0;$i<count($ageCategory);$i++){
echo $ageCategory[$i];
echo ',';
}
?>
],
},
options: {
responsive: true
}
};
$(function () {
var ctx126 = document.getElementById('canvas6').getContext('2d');
window.myPie = new Chart(ctx126 , canvas6);
});
So, I tried something like this
for(var k=0;k<3;k++){
var q=26;
var canvas+q = {
type: 'doughnut',
data: {
datasets: [{
data: [
<?php
for($i=0;$i<count($dataAgeGrp[k]);$i++){
echo $dataAgeGrp[k][$i];
echo ',';
}
?>
],
backgroundColor: [
<?php
for($i=0;$i<count($ageCategory);$i++){
$rand = str_pad(dechex(rand(0, 0xFFFF00)), 6, 0, STR_PAD_LEFT);
echo('"#' . $rand.'"');
echo ",";
}
?>
],
label: 'Pie Chart'
}],
labels: [
<?php
for($i=0;$i<count($ageCategory);$i++){
echo $ageCategory[$i];
echo ',';
}
?>
],
},
options: {
responsive: true
}
};
$(function () {
var ctx1+q = document.getElementById('canvas'+q).getContext('2d');
window.myPie = new Chart(ctx1+q , canvas+q);
});
q=q+1;
But I am getting this error
Use of undefined constant k - assumed 'k' (this will throw an Error in a future version of PHP)
How do I fix it?
If you can use PHP variables in your JavaScript code, the contrary is not possible. The only way to pass JavaScript variable to PHP code is by request (reload page with GET/POST parameters or AJAX request)

Use a JS string variable passed in as a parameter as the value of a data parameter in chart.js?

This is the relative Javascript that is not working quite right. The parameter thisChartData is a string and it alerts just fine; it's generated by a PHP script elsewhere (but that's not important).
If I copy and paste what the alert output into the data section the chart generates fine. But for some reason I can't use the parameter name in the data section
function drawChart( thisChartData, thisChartTitle ) {
var ctx = $("#my-chart");
alert(thisChartData); // alerts-> '131', '1043', '144', '43'
//chart data
var ctxData = {
datasets: [{
data: [ thisChartData ], //using the paramter variable doesn't work
backgroundColor: [ <?php echo $bg_color_list; ?> ]
}]
};
Meanwhile the code below works fine, I need the data to be variable depending on what I pass to the function because I'm going to have several data sets I want to scroll through.
function drawChart( thisChartData, thisChartTitle ) {
var ctx = $("#my-chart");
alert(thisChartData); // alerts-> '131', '1043', '144', '43'
//chart data
var ctxData = {
datasets: [{
data: [ '131', '1043', '144', '43' ],
backgroundColor: [ <?php echo $bg_color_list; ?> ]
}]
};
data: [ thisChartData ] should just be data: thisChartData, and when you call drawChart, pass in an array. E.g.:
function drawChart( thisChartData, thisChartTitle ) {
var ctx = $("#my-chart");
//chart data
var ctxData = {
datasets: [{
data: thisChartData, // <======
backgroundColor: [ <?php echo $bg_color_list; ?> ]
}]
};
and
drawChart(['131', '1043', '144', '43'], "title");

VizFrame combined chart with multiple Y-Axis

I have a problem with the VizFrame control of the SAPUI5 Framework. I want to display some data in an complex chart with two Y-axes. My data model looks like this:
{
"d" : {
"results" : [
{
"DataA" : "2",
"DataB" : "4",
"Id" : "1",
},
{
"DataA" : "3",
"DataB" : "2",
"Id" : "2",
}
]
}
}
I tried to display DataA on the left Y-Axis and DataB on the right one, while using the Id for the X-Axis. This works without problems with the VizFrame types: dual_line and dual_column.
I havent found a way to display the data as a bar (DataA on Y1) and line (DataB on Y2). My current coding looks like this:
var oModel = new sap.ui.model.json.JSONModel();
oModel.loadData("data.json");
var oDataset = new sap.viz.ui5.data.FlattenedDataset({
dimensions: [{
axis : 2,
name : oLocText.getText('Id'),
value : "{Id}"
}],
measures : [{
group : 1,
name : DataA,
value : '{DataA}'
},{
group : 2,
name: DataB,
value: '{DataB}'
}],
data : {
path : "/d/results"
}
});
oVizFrame.setDataset(oDataset);
oVizFrame.setModel(oModel);
oVizFrame.setVizType('combination');
oVizFrame.setVizProperties({
title: {
visible: true,
text: "Combined"
},
plotArea: {
colorPalette : d3.scale.category20().range(),
}});
var feedValueAxis = new sap.viz.ui5.controls.common.feeds.FeedItem({
'uid': "primaryValues",
'type': "Measure",
'values': [ DataA , DataB]
}),
feedCategoryAxis = new sap.viz.ui5.controls.common.feeds.FeedItem({
'uid': "axisLabels",
'type': "Dimension",
'values': [ Id]
});
oVizFrame.addFeed(feedValueAxis);
oVizFrame.addFeed(feedCategoryAxis);
Thank you very much for your help!
Please try:
var feedValueAxis1 = new sap.viz.ui5.controls.common.feeds.FeedItem({
'uid': "valueAxis",
'type': "Measure",
'values': [ DataA ]
}), feedValueAxis2 = new sap.viz.ui5.controls.common.feeds.FeedItem({
'uid': "valueAxis2",
'type': "Measure",
'values': [DataB]
}),
it will automatically plot DataA against left axis as bar and DataB against right axis as line.
Please be noticed that dual combination was available starting from SAPUI5 1.40.
I don´t know if your question is still relevant.
If I got your question right it´s about displaying measures as bar / line. I had a similar problem and I solved it by setting the dataShape property of plotArea:
oVizFrame.setVizProperties({
plotArea: { dataShape : {primaryAxis : ['bar','bar','bar'],
secondaryAxis : ['line', 'line', 'line']}}
});
In this example a maximum of 3 measures on each axis would be drawn as bar on axis 1 and as line on axis 2. I guess once you see this coding you know what to do when you would like to change bar vs. line.
One remark: only 'bar' and 'line' are allowed here (I checked the docu and also source code).
Best regards,
Sebastian

JSON data not showing in highstock Candlestick chart using PHP & MYSQL

I'm trying to create a highstock's candlestick chart using php and mySQL.
this is my code so far, really appreciate if anyone can help me with this:
This my code for retrieving data from mySQL database and convert it to JSON format (datachart.php):
$conn = mysql_connect("localhost", "root", "") or die (mysql_error ());
$db = mysql_select_db ("b27sim") or die (mysql_error ());
$result=mysql_query ("SELECT date, open, high, low, close FROM mb27_daily") or die (mysql_error ());
$data = array();
$count = 0;
while ($row=mysql_fetch_array($result))
{
$newdate = strtotime($row['date']) * 1000;
$data[] = array( $newdate, (float)$row['open'], (float)$row['high'], (float)$row['low'], (float)$row['close']);
$count++;
}
echo json_encode($data);
This is the result from datachart.php:
[[1350252000000,369.72,371.02,368.09,370.22],[1349820000000,366.58,369.13,364.92,368.92],[1349733600000,367.38,369.93,366.82,368.64],[1349388000000,367.28,371.85,367.2,369.9],[1349301600000,362.75,366.24,362.22,365.61],[1349215200000,363.34,363.54,361.27,362.27],[1349128800000,360.79,362.73,360.33,361.77],[1349042400000,360.75,360.75,357.94,359.46],[1348783200000,360.62,362.69,359.84,362.5],[1348696800000,356.39,361.01,355.32,359.34],[1348524000000,358,360.39,356.34,359.7],[1348437600000,357.96,360.99,355.92,356.89],[1348178400000,359.27,360.53,356.93,360.53],[1348092000000,358.74,359.31,356.51,358.01],[1348005600000,357.97,361.82,357.24,359.86],[1347919200000,359.8,360.34,356.78,358.5],[1233010800000,119.28,122.42,119.28,121.91]]
And this is my javascript code inside index.htm:
$(function() {
$.getJSON('datachart.php', function(data) {
// create the chart
chart = new Highcharts.StockChart({
chart : {
renderTo : 'container',
},
rangeSelector : {
selected : 1
},
title : {
text : 'IB27 Price'
},
series : [{
type : 'candlestick',
name : '',
data : data,
tooltip: {
valueDecimals: 2
},
dataGrouping : {
units : [
['week', // unit name
[1] // allowed multiples
], [
'month',
[1, 2, 3, 4, 6]]
]
}
}]
});
});
});
and this is my div calling the container:
<div id="container" style="height: 500px; min-width: 500px"></div>
and this is the result:
I got has not graph inside, but showing the timeline at the bottom, the date range on right top, etc.
Appreciate you guys help on this as I've been banging my head for the last 4 hours because of this... :)
Thanks,
Raz
Your data should be sorted by x (timestamps), ascending.

Categories