I am new to dojo chart. I am trying to create a stacked column chart using dojo . I am trying to show bar chart with line chart using dojo chart.Chart is appear. But here is my problem is how can i write my x-axis label name which comes from my database.I want to naming each bar's name on X-axis. My actual values comes from database. I searches from all stack overflow suggestion,dojo guides and from others but i could not found any proper solution.So i request to you please help me where my code is wrong.So here i can rectify me for futures.
Here is my code index.php
<?php
include "connection.php";
$array = array();
$array1 = array();
$array2 =array();
$query1 = "SELECT name,rate1,rate2 FROM TEST";
$result = mysql_query($query1) or die ('Could not find Projects');
while ($rows = mysql_fetch_array($result)){
$array1[]=$rows['name'];
$array1[]=$rows['rate1'];
$array2[]=$rows['rate2'];
}
print_r($array1);
print_r (json_encode($array1,JSON_NUMERIC_CHECK));
print_r (json_encode($array2,JSON_NUMERIC_CHECK));
<html><head>
<link rel="stylesheet" href="dijit/themes/tundra/tundra.css">
<script>dojoConfig = {parseOnLoad: true}</script>
<script src='dojo/dojo.js'></script>
<script type="text/javascript">
require(["dojox/charting/Chart",
//"dojox/charting/plot2d/Lines",
"dojox/charting/axis2d/Default",
"dojox/charting/plot2d/StackedColumns",
"dojox/charting/action2d/Tooltip",
"dojo/ready",
"dojox/charting/widget/SelectableLegend"],
function(Chart, Default, StackedColumns, Tooltip, ready, SelectableLegend) {
ready(function() {
var chart1 = new Chart("chart1");
chart1.addPlot("stackedColumnsPlot", {
type: StackedColumns,
lines: true,
areas: true,
markers: true,
tension: "S"
});
chart1.addPlot("linesPlot", {
type: Lines,
markers: true,
stroke: {
width: 2
},
tension: 2
});
chart1.addAxis("x");
chart1.addAxis("y", {
vertical: true
});
chart1.addSeries("Series 1", <?php echo json_encode($array1,JSON_NUMERIC_CHECK); ?>
, {
plot: "stackedColumnsPlot",
stroke: {
color: "blue"
},
fill: "lightblue"
});
chart1.addSeries("Series 2", <?php echo json_encode($array2,JSON_NUMERIC_CHECK); ?>, {
plot: "stackedColumnsPlot",
stroke: {
color: "green"
},
fill: "lightgreen"
});
new Tooltip(chart1, "stackedColumnsPlot", {
text: function(chartItem) {
console.debug(chartItem);
return "Value: " + chartItem.run.data[chartItem.index] + "; Stacked Value: " + chartItem.y;
}
});
chart1.render();
new SelectableLegend({
chart: chart1,
horizontal: false
}, "chart1SelectableLegend");
});
});
</script>
This is my code what i am writing for stacked column chart.So suggest me how can i write label name of x-axis in my chart which comes from my database.
Add a label to the x axis:
Here are a few examples:
Use title property for one label for the entire axis.
chart.addAxis("x", {
min: 0, max: 100,
fontColor: "blue",
vertical: true,
fixLower: "major", fixUpper: "major",
title: "X axis title",
titleFont: "bold bold bold 12pt Arial,sans-serif",
titleOrientation: "axis"
});
For labels on each tick mark on the x axis:
var xAxisLabels = [{text: "Today",value: 1},{text: "-1",value: 2},{text: "-2",value: 3},{text: "-3",value: 4},{text: "-4",value: 5},{text: "-5",value: 6},{text: "-6",value: 7},{text: "WK-1",value: 8},{text: "WK-2",value: 9},{text: "WK-3",value: 10},{text: "WK-4",value: 11}];
chart.addAxis("x", {
labels: xAxisLabels,
fontColor: "blue",
majorTicks:true,
majorTickStep:1,
minorTicks:false,
max: 11
});
Not sure about the database part
Related
I am trying to plot chart using Chart.JS based on my data from database. Here number of Labels and their values will come directly from the query result. Here is my code:
<script type="text/javascript">
window.onload = function () {
<?php
function getValsOfCategoryLabels(){
$yValsWithLabels = "";
......
// some codes to make query on db and get result in $queryResult variable
......
......
foreach($queryResult as $data){
$x0 = $data0['name'];
$total = $data0['total'];
$yValsWithLabels = $yValsWithLabels. "{y: ".$total.", label: \"".$x0."\"}, ";
}
return $yValsWithLabels;
}
?>
var categoryLabelsNdVals = [<?php echo getValsOfCategoryLabels() ?>];
var hourlyCategoryBarChart = new CanvasJS.Chart("columnchartContainer", {
animationEnabled: true,
axisX: {
labelFontSize: 16
},
axisY: {
title: "",
labelFontSize: 13
},
legend: {
verticalAlign: "bottom",
horizontalAlign: "center",
fontSize: 16
},
theme: "theme2",
data: [
{
type: "column",
showInLegend: true,
legendMarkerColor: "grey",
legendText: "Name of Category",
dataPoints: categoryLabelsNdVals
}
]
});
hourlyCategoryBarChart.render();
Now for the given datapoints (which is in "{y: Some_Value, label: Some_Name}" format) I am not getting any chart as output, unless I explicitly declare all the y-axis values and label names myself, which fails reflect database info.
What is the right way to accomplish my objective?
This question already exists:
Stacked Bar Flot Chart - labels inside each series of Stacked Bar [duplicate]
Closed 8 years ago.
I would like to show labels on each series of the stacked bar.Any idea please. I have been looking with no luck.
For example if you have blue series text will be blue on the series of the stacked bar and so on.
It should be something like that as you can see in the image :
Here is my code:-
<div id="placeholder" style="width:600px;height:300px;"></div>
var data = [
{label: 'foo', color:'red', data: [[1,300], [2,300], [3,300], [4,300], [5,300]]},
{label: 'bar', color:'blue', data: [[1,800], [2,600], [3,400], [4,200], [5,0]]},
{label: 'baz', color:'yellow', data: [[1,100], [2,200], [3,300], [4,400], [5,500]]},
];
$.plot($("#placeholder"), data, {
series: {
stack: 1,
bars: {
show: true,
lineWidth: 1,
barWidth: 0.8,
order: 1,
fill: true,
label: {
show: true,
radius:0.7,
formatter: function(label, series) {
var result =[ <?php echo $red; ?> ,<?php echo $blue; ?> ,<?php
echo $yellow; ?>
];
if ( label == "red")
{
return '<div style="font-size:13px; text-align:center; left:-340px; top:-338px;
position:absolute; color:white;">'+label+'<br/>'+(result[0])+'</div>';
}
else if (label == "blue")
{
return '<div style="font-size:13px; text-align:center; left:-343px; top:-228px;
position:absolute; color:white;">'+label+'<br/>'+(result[1])+'</div>';
}
else if (label == "yellow")
{
return '<div style="font-size:13px; text-align:center; left:-325px; top:-220px;
position:absolute; color:white;">'+label+'<br/>'+(result[2])+'</div>';
}
},
background: {
opacity: 0.8,
}
}
},
yaxis : {
min : 0,
tickLength: 0
} ,
xaxis: {
tickLength: 0,
axisLabel: "Date",
axisLabelUseCanvas: true,
axisLabelFontSizePixels: 12,
axisLabelFontFamily: 'Arial',
axisLabelPadding: 3,
color: "#838383",
timeformat: "%b/%y"
}
}
});
You should be able to use the valuelabels plugin to get this to work.
Reference: https://github.com/winne27/flot-valuelabels/wiki
Download: https://github.com/winne27/flot-valuelabels/blob/master/jquery.flot.valuelabels.js
Basic example: http://jsfiddle.net/WetNoodles/6b8n4nhe/1/
With the plugin, you can specify these options on each data series:
valueLabels: {
show: true,
valign: 'middle'
}
I am trying to update jqplot PieChart via JS since yesterday and I am not having any breakthrough with this. I have searched online and cant seem to get any solution work
The chart data is saved in session and this session is continuously being updated by the application.
This is what the JSON looks like
[ ['Take home pay', 44228.33], ['Tax', 8771.67], ['Super', 4162.5 ], ['Regular expenses', 0 ], ['Unallocated', 44228.33], ['Testing', 8000] ]
The chart loads fine when the user navigates to the page for the first time.
This is the DIV where the chart loads
<div id="savings_expense" class="jqplot-target"></div>
This is the jqplot JS when the page loads which works fine
$(document).ready(function () {
var storedData = <?php echo $_SESSION['chart_data'] ?>;
var plot1;
jQuery.jqplot.config.enablePlugins = false;
plot1 = jQuery.jqplot('savings_expense', [storedData],
{
seriesDefaults: {
renderer: jQuery.jqplot.PieRenderer
},
legend: {
show: true,
rendererOptions: {
numberRows: 6
},
placement: 'outside',
location: 's',
marginTop: '15px'
}
}
);
});
This is the button that user clicks to update the chart.
<li onclick="updateGraph()">YOUR TAKE-HOME PAY</li>
I have tried two ways to update the PieChart
Solution 1
In this solution I get the error Uncaught TypeError: Cannot read property 'replot' of undefined.
var storedData = <?php echo $_SESSION['chart_data'] ?>;
var plot1;
function renderGraph() {
plot1.replot({
seriesDefaults: {
renderer: jQuery.jqplot.PieRenderer
},
legend: {
show: true,
rendererOptions: {
numberRows: 6
},
placement: 'outside',
location: 's',
marginTop: '15px'
}
});
}
function updateGraph() {
alert('updateGraph');
var newVal = <?php echo $_SESSION['chart_data'] ?>;
storedData.push(newVal);
renderGraph();
}
Solution 2
In this solution the pie chart goes blank but the legends stay
var storedData = <?php echo $_SESSION['SMP']['chart_data'] ?>;
var plot1;
function renderGraph() {
if ( plot1) {
plot1.destroy();
}
jQuery.jqplot.config.enablePlugins = false;
plot1 = jQuery.jqplot('savings_expense',[storedData],
{
seriesDefaults: {
renderer: jQuery.jqplot.PieRenderer
},
legend: {
show: true,
rendererOptions: {
numberRows: 6
},
placement: 'outside',
location: 's',
marginTop: '15px'
}
}
);
}
I will really appreciate any help here. Please do not share any links as I have gone through about every solution I could find on StackOverflow and on net
You have to keep on document.ready code as it is and then add function updateGraph outside document.ready (keep all variable at global level). Also modify updateGraph, here you need to call .replot() on plot1 variable as you are only changing data and not other setting.
put id to li like this : <li id="updateGraph">YOUR TAKE-HOME PAY</li>
See below code :
// declare variable outside document.ready
var plot1;
var storedData;
$(document).ready(function () {
storedData = <?php echo $_SESSION['chart_data'] ?>;
jQuery.jqplot.config.enablePlugins = false;
plot1 = jQuery.jqplot('savings_expense', [storedData],
{
seriesDefaults: {
renderer: jQuery.jqplot.PieRenderer
},
legend: {
show: true,
rendererOptions: {
numberRows: 6
},
placement: 'outside',
location: 's',
marginTop: '15px'
}
}
);
$('#updateGraph').click(function(){updateGraph();});
});
function updateGraph() {
var newVal = <?php echo $_SESSION['chart_data'] ?>;
plot1.destroy();
plot1.series[0].data = newVal;
plot1.replot(true);
}
I'm trying to make it so that when a bar on my graph is clicked, the x-axis label of that specific bar is printed out/displayed in a span. My ultimate goal is to make it so that when a bar is clicked, another bar graph is created underneath that displays more detailed information about that specific bar, think broad information on the first graph and when a bar is clicked, more detailed information is displayed in another bar graph underneath.
Test table in my db:
x ------------- y
0 ----------- 1000
1 ----------- 2000
2 ----------- 3000
3 ----------- 4000
4 ----------- 5000
5 ----------- 6000
6 ----------- 7000
7 ----------- 8000
8 ----------- 9000
Query:
$sql = "SELECT * FROM flotTest";
$result = mysqli_query($dbc3, $sql);
while($row = mysqli_fetch_assoc($result))
{
$dataset1[] = array($row['x'],$row['y']);
}
flot js:
// BAR CHART
var percentagehrs = [];
for (var i = 0; i <= 8; i += 1){
percentagehrs.push([i, parseInt(Math.random() * 200)]);
}
var dataset = [{
label: "Percentage Hours",
data: percentagehrs,
color: "#5482FF" }];
//x-axis label and index pulled from database (testing purposes)
//I'm thinking this might be where my issue is
var ticks = <?php echo json_encode($dataset1); ?>;
$(document).ready(function () {
$.plot($("#group-flot-placeholder"), dataset, {
series: {
bars: {
show: true,
clickable: true
}
},
bars: {
align: "center",
barWidth: 0.8
},
xaxis: {
axisLabel: "Job Number",
axisLabelUseCanvas: true,
axisLabelFontSizePixels: 12,
axisLabelFontFamily: 'Verdana, Arial',
axisLabelPadding: 10,
ticks: ticks
},
yaxis: {
axisLabel: "Percent",
axisLabelUseCanvas: true,
axisLabelFontSizePixels: 12,
axisLabelFontFamily: 'Verdana, Arial',
axisLabelPadding: 3,
tickFormatter: function (v, axis) {
return v + "%";
}
},
grid: {
clickable: true,
hoverable: true,
borderWidth: 2,
backgroundColor: { colors: ["#ffffff", "#EDF5FF"] },
markings: [ { xaxis: { from: -1, to: 12 }, yaxis: { from: 100, to: 300 }, color: "#FFA5A5" }]
}
});
$("#group-flot-placeholder").UseTooltip();
$("#group-flot-placeholder").bind("plotclick", function (event, pos, item) {
if (item) {
$("#clickdata").text(" - click point " + item.dataIndex + " in " + item.series.label);
plot.highlight(item.series, item.datapoint); //Output here is: - click point 0(0 being the position of the first bar) in Percentage Hours
}
});
});
What am I doing wrong and how can I make it so that when a specific bar is clicked, I can pull data from my database to another bar graph underneath for that specific bar?
You don't say what <?php echo json_encode($dataset1); ?> resolves to, but it should be in the form of:
var ticks = [[0,"A"],[1,"B"],[2,"C"],[3,"D"],[4,"E"],[5,"F"],[6,"G"],[7,"H"],[8,"I"]];
So, in your click callback:
$("#group-flot-placeholder").bind("plotclick", function (event, pos, item) {
if (item) {
var tickClicked = item.series.xaxis.ticks[item.dataIndex].label;
$("#clickdata").text(tickClicked);
}
});
Here's a fiddle demonstration.
I tried with my other two scripts(line chart and pie chart) but the flot doesn't draw the bars chart... can you help me with this...I think the error is in the javascript..
The library:
<script src="js/jquery.flot.min.js"></script>
<script src="js/jquery.flot.pie.min.js"></script>
<script src="js/jquery.flot.stack.js"></script>
<script src="js/jquery.flot.resize.min.js"></script>
Here is the printdata db call:
[["junio",390],["julio",125],["agosto",50]]
Here is the script in graficayear.php:
<?php
include 'includes/configs.php';
$sql = $conn->prepare("SELECT DATE_FORMAT(start, '%M') AS mdate, SUM(honorario) AS total_mes
FROM CITAS WHERE YEAR(current_date) GROUP BY mdate DESC");
$sql->execute();
while($row = $sql->fetch(PDO::FETCH_ASSOC)) {
$datayear[] = array($row['mdate'],(int) $row['total_mes']);
}
?>
Here is the code in chartyear.php:
<?php include 'graficayear.php'; ?>
<script type='text/javascript' charset='utf-8'>
$(function () {
$.plot(
$("#baryear"),
[{
data : <?php echo json_encode($datayear);?>,
color: '#012D4C',
bars: { show: true, fillColor: '#4682b4', barWidth: (15*24*60*60*1000), align: 'center' }
}],
{
grid: { color: '#012D4C' },
xaxis: {
mode: 'time',
tickDecimals: 0,
tickSize: [1,'month'],
autoscaleMargin: 0.001
}
}
);
});
</script>
And the DIV with the ID:
<?php include 'chartyear.php'; ?>
<div id="baryear" style="width: 320px; height: 300px;"></div>
here is how my chart look like until now:
And this is the data I need to show inside of the bars chart:
You need to read the documentation on the expected data formats more carefully. Here you've specified an xAxis of type time but then have given it categories. You have to pick one way or the other.
So, given the format of you json data, here the shortest path to do what you want:
// given your data
var datayear = [["junio",390],["julio",125],["agosto",50]];
// split it into a data array and a ticks array
var data = [], ticks = [];
for (var i = 0; i < datayear.length; i++) {
data.push([i,datayear[i][1]]); // note that the x value is numeric
ticks.push([i,datayear[i][0]]); // and that the x value is matched to a "category"
}
$.plot(
$("#baryear"),
[{
data : data,
color: '#012D4C',
bars: { show: true, fillColor: '#4682b4', align: 'center' }
}],
{
grid: { color: '#012D4C' },
xaxis: {
ticks: ticks
}
});
Fiddle here.
Produces: