google charts - Bar color - charts

How can i change color of bar "BLACK"? Now its green
function drawChart() {
var data = google.visualization.arrayToDataTable([
['MODEL', 'CYAN', 'MAGENTA', 'YELLOW', 'BLACK'],
<?php
while($row = mysqli_fetch_array($exec))
{
echo"['$row[1] - $row[0]', $row[5], $row[4], $row[3], $row[2]],";
}
?>
]);
var options = {
chart: {
title: "Stan tonerów z <?php echo $date ?>",
titleTextStyle:{fontSize:76,},
subtitle: ''
},
bars: 'horizontal' // Required for Material Bar Charts.
};
i tried {role: 'style'} but it dosent work

try the config option for: colors
var options = {
chart: {
title: "Stan tonerów z <?php echo $date ?>",
titleTextStyle:{fontSize:76,},
subtitle: ''
},
colors: ['CYAN', 'MAGENTA', 'YELLOW', 'BLACK'],
bars: 'horizontal' // Required for Material Bar Charts.
};

Related

Yii2 ChartJs throws A non-numeric value encountered error at page

I have installed a 2amigos/yii2-chartjs-widget to my yii2 project via composer and after installing it I am trying to tun the example as shown in the documentation.
<?php
ChartJs::widget([
'type' => 'pie',
'id' => 'structurePie',
'options' => [
'height' => 200,
'width' => 400,
],
'data' => [
'radius' => "90%",
'labels' => ['Label 1', 'Label 2', 'Label 3'], // Your labels
'datasets' => [
[
'data' => ['35.6', '17.5', '46.9'], // Your dataset
'label' => '',
'backgroundColor' => [
'#ADC3FF',
'#FF9A9A',
'rgba(190, 124, 145, 0.8)'
],
'borderColor' => [
'#fff',
'#fff',
'#fff'
],
'borderWidth' => 1,
'hoverBorderColor'=>["#999","#999","#999"],
]
]
],
'clientOptions' => [
'legend' => [
'display' => false,
'position' => 'bottom',
'labels' => [
'fontSize' => 14,
'fontColor' => "#425062",
]
],
'tooltips' => [
'enabled' => true,
'intersect' => true
],
'hover' => [
'mode' => false
],
'maintainAspectRatio' => false,
],
'plugins' =>
new \yii\web\JsExpression('
[{
afterDatasetsDraw: function(chart, easing) {
var ctx = chart.ctx;
chart.data.datasets.forEach(function (dataset, i) {
var meta = chart.getDatasetMeta(i);
if (!meta.hidden) {
meta.data.forEach(function(element, index) {
// Draw the text in black, with the specified font
ctx.fillStyle = rgb(0, 0, 0);
var fontSize = 16;
var fontStyle = normal;
var fontFamily = Helvetica;
ctx.font = Chart.helpers.fontString(fontSize, fontStyle, fontFamily);
// Just naively convert to string for now
var dataString = dataset.data[index].toString()+'%';
// Make sure alignment settings are correct
ctx.textAlign = center;
ctx.textBaseline = middle;
var padding = 5;
var position = element.tooltipPosition();
ctx.fillText(dataString, position.x, position.y - (fontSize / 2) - padding);
});
}
});
}
}]')
])
?>
But when I refresh my page I am getting this error
A non-numeric value encountered
The error occurs at var dataString = dataset.data[index].toString()+'%';
I have been trying to solve this issue but I couldn't find anything
Any help would be highly appreciated.
Its because you are not escaping the quotes correctly you need to escape the single quotes in the statement
var dataString = dataset.data[index].toString()+' % ';
because your outer quotes in the new yii\db\Expression() are using single quotes to wrap the whole javascript, so change the line to
var dataString = dataset.data[index].toString()+\' % \';

How can show values in bar - GoogleChart/SQL

I need to put the values ​​inside the bar or outside it but I need you to show me the value, I've already seen some examples but the arrays tables have more than one line with the values ​​placed in the hand, but mine connects by SQL
How can I place the values ​​on my bar chart?
A user showed me this answer, but in "var data = google.visualization.arrayToDataTable"
It returns the values ​​in the rows
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Descr', 'Downlink', 'Uplink'],
['win7protemplate', 12, 5],
['S60', 14, 5],
['iPad', 3.5, 12], ]);
http://jsfiddle.net/heennkkee/rekso9t6/
But mine only has 1 line per account that pull this value from MySQL
google.load("visualization", "1", {packages:["barchart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['quantidade_demanda','COUNT(Subclasse)'],
<?php
$query = "SELECT COUNT(Subclasse), Subclasse AS quantidade_demanda FROM demandas_portal WHERE Categoria = 'Demanda Ambiental' GROUP BY Subclasse";
$exec = mysqli_query($con,$query);
while($row = mysqli_fetch_array($exec)){
echo "['".$row['quantidade_demanda']."',".$row['COUNT(Subclasse)']."],";
}
?>
]);
Would I have to add a new variable? because I only have these options
var options = {
colors: ['#00544d'],
width: 500,
height: 250
};
options.legend = 'none';
var chart = new google.visualization.BarChart(document.getElementById('chart_demanda'));
chart.draw(data,options);
}
if you are referring to displaying annotations on the bars,
you need to add another column to the data table,
using an annotation role...
add the annotation role to the column heading, here...
['quantidade_demanda','COUNT(Subclasse)', {role: 'annotation', type: 'string'}], // <-- add annoation role to column heading
then repeat the column value as a string, here...
echo "['".$row['quantidade_demanda']."',".$row['COUNT(Subclasse)'].",'".$row['COUNT(Subclasse)']."'],"; // <-- add value of annotation, repeat column value as string
see following snippet...
var data = google.visualization.arrayToDataTable([
['quantidade_demanda','COUNT(Subclasse)', {role: 'annotation', type: 'string'}], // <-- add annoation role to column heading
<?php
$query = "SELECT COUNT(Subclasse), Subclasse AS quantidade_demanda FROM demandas_portal WHERE Categoria = 'Demanda Ambiental' GROUP BY Subclasse";
$exec = mysqli_query($con,$query);
while($row = mysqli_fetch_array($exec)){
echo "['".$row['quantidade_demanda']."',".$row['COUNT(Subclasse)'].",'".$row['COUNT(Subclasse)']."'],"; // <-- add value of annotation, repeat column value as string
}
?>
]);

3 Google Charts on a page displays nothing

currently I am trying to show 3 Google Charts on a page, but the page is blank, it does not display any of the charts. Originally the 1st chart was displayed, then it worked but ever since I attached the 2nd one (even if I deleted that so only the 1st one would be shown again), the page I have is totally blank and I don't know why.
Could you please help me?
Here is my code (I set the $conn and $_SESSION variables at the top of my page):
EDIT: Here is a picture about the source code in my browser:
[![sourcecode][1]][1] What I don't understand is that it looks like it would expect other values to data1 and data2 and that is why the charts are not displayed...
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Dashboard</title>
<link rel="stylesheet" href="styles.css">
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
// Load Charts and the corechart package.
google.load('current', callback: drawCharts, {packages:['column', 'pie']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawCharts);
// Callback that creates and populates a data table, instantiates the pie chart, passes in the data and draws it.
function drawCharts() {
var data1 = google.visualization.arrayToDataTable([
['Classification', 'Number of assets'],
<?php
if ($_SESSION['user_type'] == 'admin') {
$sql = "SELECT Classification, count('Classification') as count FROM `assets` GROUP BY Classification ORDER BY FIELD(Classification, 'high', 'medium', 'low')";
}else{
$sql = "SELECT Classification, count('Classification') as count FROM `assets` WHERE Responsible =".$_SESSION['name']." GROUP BY Classification ORDER BY FIELD(Classification, 'high', 'medium', 'low')";
}
$result = mysqli_query($conn,$sql);
while ($result2=mysqli_fetch_array($result)) {
echo "['".$result2['Classification']."',".$result2['count']."],";
}
?>
]);
var data2 = google.visualization.arrayToDataTable([
['Risks', 'Percentage'],
<?php
if ($_SESSION['user_type'] == 'admin') {
$sql = "SELECT Compliant = (SELECT count('id') FROM `risks` WHERE targetrisk >= residualrisk), Non-compliant = (SELECT count('id') FROM `risks` WHERE targetrisk < residualrisk) FROM risks ";
}else{
$sql = "SELECT Compliant = (SELECT count('id') FROM `risks` WHERE responsible =".$_SESSION['name']." AND targetrisk >= residualrisk), Non-compliant = (SELECT count('id') FROM `risks` WHERE ".$_SESSION['name']." AND targetrisk < residualrisk) FROM risks ";
}
$results = mysqli_query($conn,$sql);
while ($result2=mysqli_fetch_array($results)) {
echo "['".$result2['Compliant']."',".$result2['Non-compliant']."],";
}
?>
]);
var data3 = google.visualization.arrayToDataTable([
['Assets', 'Percentage'],
<?php
if ($_SESSION['user_type'] == 'admin') {
$sql = "SELECT count('Asset_name') as Assets, count(`risks`.`assettag`) as Compliant assets FROM `assets`, `risks` JOIN `assettag` ON `assets`.`Tag` = `risks`.`assettag` ";
}else{
$sql = "SELECT count('Asset_name') as Assets, count(`risks`.`assettag`) as Compliant assets FROM `assets`, `risks` JOIN `assettag` ON `assets`.`Tag` = `risks`.`assettag` AND responsible =".$_SESSION['name']."";
}
$results = mysqli_query($conn,$sql);
while ($result2=mysqli_fetch_array($results)) {
echo "['".$result2['Assets']."',".$result2['Compliant assets']."],";
}
?>
]);
var options1 = {
title: 'Asset classification',
legend: { position: 'none' },
width: 900,
height: 500
};
var options2 = {
title: 'Risk compliance',
legend: { position: 'none' },
width: 900,
height: 500
};
var options3 = {
title: 'Asset compliance',
legend: { position: 'none' },
width: 900,
height: 500
};
var chart1 = new google.visualization.ColumnChart(document.getElementById("columnchart"));
chart1.draw(data1, options1);
var chart2 = new google.visualization.PieChart(document.getElementById("piechart"));
chart2.draw(data2, options2);
var chart3 = new google.visualization.PieChart(document.getElementById("piechart2"));
chart3.draw(data3, options3);
}
</script>
</head>
<body>
<div id="columnchart"></div>
<br>
<div id="piechart" ></div>
<br>
<div id="piechart2" ></div>
</body>
</html>
[1]: https://i.stack.imgur.com/f2u3D.png

Pie chart not showing slice

I create a pie chart using google services. the problem is that i want to show credit and debit in pie chart, but output comes only in one color. Here is my query.
$data = mysqli_query($link, "select SUM(pay_payable) as debit, SUM(pay_paid) as credit from purchasers_payment where p_id = '$pur_id'");
and here is my chart setting.
var data = google.visualization.arrayToDataTable([
['Debit', 'Credit'],
<?php
while($row = mysqli_fetch_array($data))
{
echo "['".$row['debit']."',".$row['credit']."],";
}
?>
]);
var options = {
is3D: true,
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
here is mine code output
enter image description here
and i want output like this:
enter image description here
the data format for a PieChart uses rows for each slice
to get two slices, you need two rows of data...
['Label', 'Value'],
['Debit', 10000],
['Credit', 2000]
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var data = google.visualization.arrayToDataTable([
['Label', 'Value'],
['Debit', 10000],
['Credit', 2000]
]);
var options = {
is3D: true,
height: 300
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="piechart"></div>
try the following php...
var data = google.visualization.arrayToDataTable([
['Label', 'Value'],
<?php
while($row = mysqli_fetch_array($data))
{
echo "['Debit',".$row['debit']."],['Credit',".$row['credit']."],";
}
?>
]);

cakePHP + extjs row editor and REST

I've implemented REST routing in cakePHP to properly route REST style requests to the proper methods in my controller.
This is what I've added to my routes.php
Router::mapResources(array('object_fields'));
This properly routes the REST requests to my index/add/edit/delete methods inside my controller.
In my EXTJS grid I am using the row editor with a restful store to achieve CRUD behavior.
Here is the code for my grid
myapp.object_field_grid = Ext.extend(Ext.grid.GridPanel, {
closable: true,
stripeRows: true,
frame: true,
viewConfig: {
forceFit: true
},
editor: new Ext.ux.grid.RowEditor({
saveText: 'Update',
}),
onAdd : function(btn, ev){
var u = new this.store.recordType({
name : '',
type: '',
});
this.editor.stopEditing();
this.store.insert(0, u);
this.editor.startEditing(0);
},
onDelete : function(){
},
initComponent: function() {
var proxy = new Ext.data.HttpProxy({
url: 'object_fields/',
});
var reader = new Ext.data.JsonReader({
totalProperty: 'totalCount',
successProperty: 'success',
idProperty: 'id',
root: 'data',
messageProperty: 'message'
}, [
{name: 'id'},
{name: 'name', allowBlank: false},
{name: 'type', allowBlank: false},
]);
var writer = new Ext.data.JsonWriter({
encode: false,
});
var store = new Ext.data.Store({
baseParams: {id: this.object_id},
id: 'object_fields',
restful: true,
proxy: proxy,
reader: reader,
writer: writer,
});
store.load();
var object_field_columns = [
// {header: "id", width: 250, sortable: true, dataIndex: 'id', editor: new Ext.form.TextField({})},
{header: "name", width: 250, sortable: true, dataIndex: 'name', editor: new Ext.form.TextField({})},
{header: "type", width: 250, sortable: true, dataIndex: 'type', editor: new Ext.form.ComboBox({editable: false, store:['STRING', 'NUMBER']})},
];
var config = {
columns: object_field_columns,
store: store,
plugins: [this.editor],
//autoHeight: true,
height: 200,
tbar: [{
text: 'Add',
iconCls: 'silk-add',
handler: this.onAdd,
scope: this,
}, '-', {
text: 'Delete',
iconCls: 'silk-delete',
handler: this.onDelete,
scope: this,
}, '-'],
}
Ext.apply(this, Ext.apply(this.initialConfig, config));
myapp.object_field_grid.superclass.initComponent.apply(this, arguments);
},
onRender: function() {
this.store.load();
myapp.object_field_grid.superclass.onRender.apply(this, arguments);
}
});
Ext.reg('object_field_grid', myapp.object_field_grid); // register xtype
My GET/POST requests are being properly routed to my index/add methods inside my controller and I am able to easily retrieve the paramaters that I pass it in the request.
My problem is with the update functionality PUT request. The PUT request does get successfully routed to my edit method inside the controller.
This is what the request looks like in firebug
http://server.local/object_fields/20
JSON
data
Object { name="test7777777777", more...}
id
"18"
Source
{"id":"18","data":{"name":"test7777777777","id":"20"}}
Inside my edit method I'm not receiving my array that I passed through the PUT request.
When I dump $this->params inside my edit method this is what is in the array.
([id] => 20
[named] => Array
(
)
[pass] => Array
(
[0] => 20
)
[controller] => object_fields
[action] => edit
[[method]] => PUT
[plugin] =>
[url] => Array
(
[ext] => html
[url] => object_fields/20
)
[form] => Array
(
)
[isAjax] => 1
)
How can I properly receive my array through the PUT request inside my edit method?
UPDATE:
I am able to retrieve my array using the following code inside the edit method
function edit($id){
$this->autoRender = false;
echo 'edit';
$raw = '';
$httpContent = fopen('php://input', 'r');
while ($kb = fread($httpContent, 1024)) {
$raw .= $kb;
}
fclose($httpContent);
$params = array();
parse_str($raw, $params);
print_r($params);
}
The question is now why does cakePHP not do this automaticly?
put this in your app_controller.php:
public function beforeFilter() {
if (
isset($this->RequestHandler) &&
$this->RequestHandler->requestedWith('json') &&
(
$this->RequestHandler->isPost() ||
$this->RequestHandler->isPut()
)
) {
$jsonData = json_decode(utf8_encode(trim(file_get_contents('php://input'))), true);
if (is_array($jsonData)) {
$this->data = $jsonData;
unset($jsonData);
}
}
}