Jqplot pie chart rendering only lines - jqplot

am loading jqplot corresponding files dynamically and passed data to the and chart div but at sometimes am getting the graph and some other time am not getting the graph my code as follows i maid an ajax call to get the values and passed to the graph in object st and the output am getting is shown here http://i43.tinypic.com/wcfns0.png please help me function
jsFunction3(xyz) {
jQuery.getCSS = function( url, media )
{
jQuery( document.createElement('link') ).attr({ href: url, media: media || 'screen', type: 'text/css', rel: 'stylesheet' }).appendTo('head'); };
$.getCSS('/redkanproject/plugins/jqplot-0.1/css/jqplot/jquery.jqplot.css','print');
$.getScript('/redkanproject/plugins/jqplot-0.1/js/jqplot/jquery.jqplot.min.js',
function() { }); $.getScript('/redkanproject/plugins/jqplot-0.1/js/jqplot/excanvas.min.js', function() { });
$.getScript('/redkanproject/plugins/jqplot-0.1/js/jqplot/plugin/jqplot.pieRenderer.min.js', function() { });
var JSONObject = new Object;
JSONObject.id =xyz;
JSONstring = JSON.stringify(JSONObject);
var url = "${createLink(controller:'page', action:'example4')}"; new Ajax.Request(url, { method:'post', contentType:'application/json', postBody:JSONstring, asynchronous:true, onSuccess: function (res) {
st=(res.responseJSON)
x="chart" // this is my div to display chart
var plot1 = $.jqplot (x, [st], { title: 'Bianual Reviews percentage', grid: {
background:'#834100', shadow: true,borderWidth: 0, borderColor: 'white',shadowDepth: 0}, seriesDefaults: {
// Make this a pie chart.
renderer: $.jqplot.PieRenderer, rendererOptions: {
// Put datalabels on the pie slices.
// By default, labels show the percentage of the slice.
sliceMargin:6,
showDataLabels: true
}
},
legend: { show:true, location: 'e' } } );
$(x).bind('jqplotDataClick', function(ev,seriesIndex, pointIndex, data)
{ alert(" data: "+data); }
);
}
})//ajax }
------------------------------------------------------------------------

I had a similar issue and it turned out that I had a global style on the table element which sets the width to 100%.
eg
table{
width:100%
}
I changed that to auto and everything displayed correctly
table{
width:auto;
}
Hope that helps :-)

Related

Leaflet PointToLayer Style on AJAX Loaded GeoJson Data

I'm having a bit of difficulty fixing the default point style on my Leaflet map, currently the points appear in the correct positions after being loaded via ajax.
But the current code does not alter the style and I am left with the default light-blue circle styling of the points:
function addressStyle(feature) {
return {
color: '#000',
fillColor: '#199900',
fillOpacity: 0.5,
radius: 100,
};
}
var address_points = new L.geoJson('', {
pointToLayer: function (feature, latlng) {
return L.circleMarker(latlng, addressStyle);
},
onEachFeature: function (feature, layer) {
layer.bindPopup('<h1>'+feature.properties.address+'</h1>');
},
});
address_points.addTo(map);
$.ajax({
dataType: "json",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: "{{url('/addresses/geojson')}}",
success: function(data) {
$(data.features).each(function(key, data) {
address_points.addData(data);
});
},
error: function(data){
}
});
Is there a better way to handle this? I am just getting into AJAX loading of related GeoJSON data but am stuck on how to proceed with styling of this features when I am having no difficulty with my other layers that aren't points.
If you want to apply the style to all layers (except markers) then change your code to:
var address_points = new L.geoJson('', {
style: addressStyle,
pointToLayer: function (feature, latlng) {
return L.circleMarker(latlng);
},
onEachFeature: function (feature, layer) {
layer.bindPopup('<h1>'+feature.properties.address+'</h1>');
},
});
When you only want to apply the style to the CircleMarker you need to pass the style as object and not as function.
You can simply call the addressStyle function:
var address_points = new L.geoJson('', {
pointToLayer: function (feature, latlng) {
return L.circleMarker(latlng, addressStyle());
},
onEachFeature: function (feature, layer) {
layer.bindPopup('<h1>'+feature.properties.address+'</h1>');
},
});
or define addessStyle as object:
var addressStyle = {
color: '#000',
fillColor: '#199900',
fillOpacity: 0.5,
radius: 100,
};
var address_points = new L.geoJson('', {
pointToLayer: function (feature, latlng) {
return L.circleMarker(latlng, addressStyle);
},
onEachFeature: function (feature, layer) {
layer.bindPopup('<h1>'+feature.properties.address+'</h1>');
},
});

How to fetch data from DB on Chart.js using Laravel?

I want to show data from database on chart and I have shown return response I need to fetch on chart but I don't know how to do that does anyone have an idea?
Return response:
[
"Joylinkhk: 13,",
"HorizonTechnologies: 2,",
"Alahazrat: 9,",
"j2w: 0,"
]
Chart script:
<script>
var barChartData = {
labels: ['Joylinhk', 'HorizonTechnologies','Alahazrat','j2w'],
datasets: [{
label: "",
backgroundColor: window.chartColors.blue,
data: [13, 2,9,0],
}
]
};
window.onload = function() {
var ctx = document.getElementById('canvas').getContext('2d');
window.myBar = new Chart(ctx, {
type: 'bar',
data: barChartData,
options: {
title: {
display: true,
text: 'Project Report Chart'
}
,
tooltips: {
mode: 'index',
intersect: false
}
,
responsive: true,
scales: {
xAxes: [{
stacked: true,
}
],
yAxes: [{
stacked: true
}
]
}
}
}
);
};
</script>
I do This more than one time
first of all you should Include Google Chart in Your Blade File
Let's See The controller function that return data to the chart
I make a function called getAreaChart()
public function getAreaChart():array {
$data = DB::table('companies')->get();
$array[]=['area','counts'];
foreach ($data as $key=>$da):
$array[++$key] = [Area::find($da->area)->area,intVal($da->count)];
endforeach;
return $array;
}
for the function that return data to view and displayed in chart, I call the function and don't forget to json_encode the result
public function home()
{
$array = $this->getAreaChart();
return view('admin.home')->with('companies', json_encode($array));;
}
in the blade file , I make a div with id pie_chart
<div id="pie_chart" style="width:510px; height:408px;background: transparent">
and the script should be like this
<script type="text/javascript">
var analytics = <?php echo $companies; ?>
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart()
{
var data = google.visualization.arrayToDataTable(analytics);
var options = {
title : ''
};
var chart = new google.visualization.PieChart(document.getElementById('pie_chart'));
chart.draw(data, options);
}
</script>
You can change the chart by change the value corechart see google chart doc
this is example that I follow
Google Charts Docs
google.charts.load('current', {'packages':['corechart']});
and this is the google charts types
Google Charts Types
I hop that helpful ;)
happy code

How to use values from an ajax request in google charts?

I am creating an array of objects using Ajax to use as values in a google line chart, however the values do not render even though I can view them through the console.
I have tried using ajax complete function to call the charts once the values are set but it still doesn't work, I suspect it's due to scoping but I don't know how to resolve it. here is my code
complete array
studentCount[
{
month:1,
count:5
},
{
month:2,
count:3
},
{
month:3,
count:9
},
{
month:4,
count:0
}
{
month:5,
count:4
}
etc...
]
code
$.ajax({
dataType: "json",
url: url,
success: function (data) {
for (var i = 0; i < data.length; i++) {
studentCount[data[i].month -1].count = data[i].count;
}
}
});
$( document ).ajaxComplete(function() {
google.charts.load('current', {
packages: ['line']
});
google.charts.setOnLoadCallback(drawLineColors);
console.log(JSON.stringify(studentCount[0].count)) //returns correct value
function drawLineColors() {
var data = google.visualization.arrayToDataTable([
['Month', '2015'],
['January', studentCount[0].count],
['Febuary', studentCount[1].count],
['March', studentCount[2].count],
['April', studentCount[3].count],
['May', studentCount[4].count],
['June', studentCount[5].count],
['July', studentCount[6].count],
['August', studentCount[7].count],
['Septembre', studentCount[8].count],
['October', studentCount[9].count],
['November', studentCount[10].count],
['December', studentCount[11].count]
]);
var options = {
hAxis: {
title: 'Month'
},
vAxis: {
title: 'Number of Students'
},
colors: ['#4285f4', '#db4437']
};
var chart = new google.charts.Line(document.getElementById('chart_div'));
chart.draw(data, google.charts.Line.convertOptions(options));
}
});
recommend loading google first, you can include the callback directly in the load statement
once loaded, then call ajax
see following working snippet, adjust as needed to get proper data,
and change error to success as the url isn't reachable from here...
google.charts.load('current', {
callback: function () {
var url = 'some url';
$.ajax({
dataType: 'json',
url: url,
error: function (data) { // <-- change 'error' to 'success' to run locally
//for (var i = 0; i < data.length; i++) {
//studentCount[data[i].month - 1].count = data[i].count;
//}
var studentCount = [
{
month:1,
count:5
},
{
month:2,
count:3
},
{
month:3,
count:9
},
{
month:4,
count:0
},
{
month:5,
count:4
}
];
var data = google.visualization.arrayToDataTable([
['Month', '2015'],
['January', studentCount[0].count],
['Febuary', studentCount[1].count],
['March', studentCount[2].count],
['April', studentCount[3].count],
['May', studentCount[4].count]
// etc...
]);
var options = {
hAxis: {
title: 'Month'
},
vAxis: {
title: 'Number of Students'
},
colors: ['#4285f4', '#db4437']
};
var chart = new google.charts.Line(document.getElementById('chart_div'));
chart.draw(data, google.charts.Line.convertOptions(options));
}
});
},
packages: ['line']
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
also, recommend using core chart instead of material,
several config options simply don't work with material charts
core chart, use package --> corechart
and chart --> google.visualization.LineChart
you can use config option theme: 'material' to get the core chart close to the look and feel of a material chart
see following working snippet...
google.charts.load('current', {
callback: function () {
var url = 'some url';
$.ajax({
dataType: 'json',
url: url,
error: function (data) { // <-- change 'error' to 'success' to run locally
//for (var i = 0; i < data.length; i++) {
//studentCount[data[i].month - 1].count = data[i].count;
//}
var studentCount = [
{
month:1,
count:5
},
{
month:2,
count:3
},
{
month:3,
count:9
},
{
month:4,
count:0
},
{
month:5,
count:4
}
];
var data = google.visualization.arrayToDataTable([
['Month', '2015'],
['January', studentCount[0].count],
['Febuary', studentCount[1].count],
['March', studentCount[2].count],
['April', studentCount[3].count],
['May', studentCount[4].count]
// etc...
]);
var options = {
hAxis: {
title: 'Month'
},
vAxis: {
title: 'Number of Students'
},
colors: ['#4285f4', '#db4437'],
theme: 'material'
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
});
},
packages: ['corechart']
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

How can I generate a real-time highchart from my database data?

I have looked at the following links Binding json result in highcharts for asp.net mvc 4 , highcharts with mvc C# and sql, HighChart Demo and many others. However, I couldn't find a working demo showing how to implement a highchart using data from a database.
Objective:
I want to generate a real time highchart line graph getting data from my database. What I want is very similar to the third link which provides a real-time highchart with randomly generated values. It is also similar by X-axis and Y-axis, for I want my x-axis to be "Time" (I have a DateTime column in my database) and y-axis to be an integer (I have a variable for that as well in my database).
Please I need help in sending the model data to my razor view.
Note that I am already using SignalR to display a realtime table. I also want to know if it can be used to automatically update the highchart as well.
Below is the code snippet of my script in the view. I have used the code provided in link 3 for generating the highchart. Please tell me where should I apply the changes on my code.
#section Scripts{
<script src="~/Scripts/jquery.signalR-2.2.0.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="~/SignalR/Hubs"></script>
<script type="text/javascript">
$(document).ready(function () {
// Declare a proxy to reference the hub.
var notifications = $.connection.dataHub;
//debugger;
// Create a function that the hub can call to broadcast messages.
notifications.client.updateMessages = function () {
getAllMessages()
};
// Start the connection.
$.connection.hub.start().done(function () {
alert("connection started")
getAllMessages();
}).fail(function (e) {
alert(e);
});
//Highchart
Highcharts.setOptions({
global: {
useUTC: false
}
});
//Fill chart
$('#container').highcharts({
chart: {
type: 'spline',
animation: Highcharts.svg, // don't animate in old IE
marginRight: 10,
events: {
load: function () {
// set up the updating of the chart each second
var series = this.series[0];
setInterval(function () {
var x = (new Date()).getTime(), // current time
y = Math.random();
series.addPoint([x, y], true, true);
}, 1000);//300000
}
}
},
title: {
text: 'Live random data'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150
},
yAxis: {
title: {
text: 'Value'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function () {
return '<b>' + this.series.name + '</b><br/>' +
Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) + '<br/>' +
Highcharts.numberFormat(this.y, 2);
}
},
legend: {
enabled: false
},
exporting: {
enabled: false
},
series: [{
name: 'Random data',
data: (function () {
// generate an array of random data
var data = [],
time = (new Date()).getTime(),
i;
for (i = -19; i <= 0; i += 1) {
data.push({
x: time + i * 1000,
y: Math.random()
});
}
return data;
}())
}]
});
});
function getAllMessages() {
var tbl = $('#messagesTable');
var data = #Html.Raw(JsonConvert.SerializeObject(this.Model))
$.ajax({
url: '/home/GetMessages',
data: {
id: data.id,
},
contentType: 'application/html ; charset:utf-8',
type: 'GET',
dataType: 'html'
}).success(function (result) {
tbl.empty().append(result);
$("#g_table").dataTable();
}).error(function (e) {
alert(e);
});
}
</script>
}
UPDATED CODE
//Highchart
Highcharts.setOptions({
global: {
useUTC: false }
});
//Fill chart
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
defaultSeriesType: 'spline',
events: {
load: $.connection.hub.start().done(function () {
alert("Chart connection started")
var point = getAllMessagesforChart();
var series = this.series[0];
setInterval(function (point) {
// add the point
series.addPoint([point.date_time, point.my_value], true, true)
}, 1000);
}).fail(function (e) {
alert(e);
})
}
}
title: {
text: 'Live random data'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000
},
yAxis: {
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: 'Value',
margin: 80
}
},
series: [{
name: 'Random data',
data: []
}]
});
function getAllMessagesforChart() {
var data = #Html.Raw(JsonConvert.SerializeObject(this.Model))
$.ajax({
url: '/home/GetMessagesforChat',
data: {
id: data.id,
},
contentType: 'application/html ; charset:utf-8',
type: 'GET',
dataType: 'html'
}).success(function (data) {
data = JSON.parse(data);
//data_graph = [].concat(data);
//$("#debug").html(data_graph);
}).error(function (e) {
alert(e);
});
return data;
//return data_graph;
}
There is an example that might help you:
http://jsfiddle.net/gh/get/jquery/1.9.1/highslide-software/highcharts.com/tree/master/samples/highcharts/demo/line-ajax/
it uses an ajax callback function.
Well, you can also have a look at my sample where I add dynamically series by clicking add button.
http://plnkr.co/edit/Sh71yN?p=preview
You only need to add data in the right structure.
Have a look at the function
$("#btnAdd").click(function()
of my code script.js
I hope it helps.
regards,
Luis

How to refresh jqplot bar chart without redrawing the chart

I have a jqplot bar chart and I want the chart data to be changed when the user changes the value on a drop-down list. That works, but the problem is the bar chart redraws, one over another, each time the user changes the values.
How can I update or reload the bars without drawing the whole thing again? Is there any property value to be set?
Chart data changes according to an ajax call:
$.ajax({
url: '/Home/ChartData',
type: 'GET',
data: { Id: Id },
dataType: 'json',
success: function (data) {
$.jqplot('chartDiv', [a, b], CreateBarChartOptions(xAxis));
}});
function CreateBarChartOptions(xAxis) {
var optionsObj = {
title: 'Stat',
axes: {
xaxis: {
renderer: $.jqplot.CategoryAxisRenderer,
ticks: xAxis
},
yaxis: { min: 0 }
},
series: [{ label: 'A' }, { label: 'B'}],
seriesDefaults: {
shadow: true,
renderer: $.jqplot.BarRenderer,
rendererOptions: {
barPadding: 8,
barMargin: 10
}
},
};
return optionsObj;
}
A reply would be highly appreciated. Thanks.
What you want to do is call jqPlot's .replot() method when you draw the new chart. Change your ajax call to look like this:
$.ajax({
url: '/Home/ChartData',
type: 'GET',
data: { Id: Id },
dataType: 'json',
success: function (data) {
$.jqplot('chartDiv', [a, b], CreateBarChartOptions(xAxis)).replot();
}});
Try having your chart object as a global variable in your script as:
var plot1 = $.jqplot('chartDiv', [a, b], CreateBarChartOptions(xAxis));
Then on success reset the data, axesScale and replot as:
var newData = [['a',1],['b',2],['c',3]];
plot1.series[0].data = newData;
plot1.resetAxesScale();
plot1.replot();
Ref: https://groups.google.com/group/jqplot-users/browse_thread/thread/59df82899617242b?pli=1
Each time before redrawing the graph, just destroy the existing1.
$.ajax({
url: '/Home/ChartData',
type: 'GET',
data: { Id: Id },
dataType: 'json',
success: function (data) {
if(plot)
{
plot.destroy();
}
var plot=$.jqplot('chartDiv', [a, b], CreateBarChartOptions(xAxis));
}});
Took me a while to find an answer for the script generated data, so I'm going to post this right here. I used a combination of the above code.
I created a global var, named plot3 within my script file. Then created the below function. When this is called with a redraw boolean, it determines if I need to destroy and redraw or draw for the first time.
What first bit of code does is gets data from my jqgrid, (which is being updated in a different function), and updates the arrays. The second bit, determines my interval ticks, on the x-axis dependent upon my length of data.
function DrawGraph(bRedraw){
var testTimes = [];
testTimes = $('#polarizationTable').jqGrid('getCol', 'TestTime', testTimes, false);
var RdgA = $('#polarizationTable').jqGrid('getCol', 'RdgA', RdgA, false);
var RdgB = $('#polarizationTable').jqGrid('getCol', 'RdgB', RdgB, false);
var readingLineA = [];
for (var i=0; i<testTimes.length; i++){
readingLineA.push([testTimes[i], RdgA[i]]);
}
var readingLineB = [];
for (var i=0; i<testTimes.length; i++){
readingLineB.push([testTimes[i], RdgB[i]]);
}
var maxX = $("#testLength").val();
var lengthX = testTimes.length;
var tickIntervalX = Math.round(maxX/10);
if(bRedraw == true)
{
plot3.destroy();
bRedraw = false;
}
if(bRedraw == false)
{
plot3 = $.jqplot('chart3', [readingLineA, readingLineB],
{
title:'Graph',
series:[{label:'Reading - A'}, {label:'Reading - B'} ],
legend:{show:true, location:'se'},
// You can specify options for all axes on the plot at once with
// the axesDefaults object. Here, we're using a canvas renderer
// to draw the axis label which allows rotated text.
axes:{
xaxis:{
label:'Minutes',
syncTicks: true,
min: 0,
numberTicks: 10,
tickInterval: tickIntervalX,
max: maxX*1.1,
labelRenderer: $.jqplot.CanvasAxisLabelRenderer,
labelOptions: {
fontSize: '12pt'
},
},
yaxis:{
label:'Data',
min: 0,
numberTicks: 10,
labelRenderer: $.jqplot.CanvasAxisLabelRenderer,
labelOptions: {
fontSize: '12pt'
}
},
}
});
}
}
Here is a full example of how to dynamically update the plot with new data without reloading the page:
<div id="chart1" style="height: 300px; width: 500px; position: relative;"></div>
<button>New data point</button>
<script type="text/javascript">
var storedData = [3, 7];
var plot1;
renderGraph();
$('button').click( function() {
doUpdate();
});
function renderGraph() {
if (plot1) {
plot1.destroy();
}
plot1 = $.jqplot('chart1', [storedData]);
}
function doUpdate() {
var newVal = Math.random();
storedData.push(newVal);
renderGraph();
}
</script>
It's a simplified version of this guy's post: JQPlot auto refresh chart with dynamic ajax data
$('#chart).html('');
chart is the DIV where chart is created.
this does the trick, nothing fancy by effective.
Maybe this will help. I on the other hand is having problem with getting replot to work at all, but i'am using a dataRenderer.
$.ajax({
url: '/Home/ChartData',
type: 'GET',
data: { Id: Id },
dataType: 'json',
success: function (data) {
$('chartDiv').empty();
$.jqplot('chartDiv', [a, b], CreateBarChartOptions(xAxis));
}});
hope this helps
jQuery(document).ready(function(){
jQuery.ajax({
url: '/review_graphs/show',
type: 'GET',
success: function (data) {
var plot1 = jQuery.jqplot('chartDiv', [data,data],
{
title: 'Bianual Reviews percentage',
series:[
{
renderer:jQuery.jqplot.BarRenderer,
label:'Average',
stackSeries: true,
dragable: {color: '#ff3366',constrainTo: 'x'},
trendline:{show: false}
},
{
label:'Trend Line',trendline:{show: false}}
],
legend: {
show: true,
placement: 'outsideGrid'
},
axesDefaults: {
tickRenderer: jQuery.jqplot.CanvasAxisTickRenderer ,
tickOptions: {
angle: -30,
fontSize: '10pt'
}
},
axes: {
xaxis: {
renderer: jQuery.jqplot.CategoryAxisRenderer
}
}
});
}});
});
The best method I got is, the div in which you're drawing, clear that before you draw your new graph.
$('#graph_area).children().remove();

Resources