I'm using Chart.js in Laravel to display data.
I'm following this tutorial, which worked for the bar chart. But now I'm trying a pie chart.
This is my controller which gets the data.
public function chart()
{
$result = \DB::table('users')
->where('userType','=','Landlord')
->orderBy('created_at', 'ASC')
->get();
return response()->json($result);
}
The view is this
<script>
var url = "{{url('/users')}}";
var Name = new Array();
var Email = new Array();
$(document).ready(function(){
$.get(url, function(response){
response.forEach(function(data){
Name.push(data.name);
Email.push(data.email);
});
var ctx = document.getElementById("canvas").getContext('2d');
var myPieChart = new Chart(ctx,{
type: 'pie',
data : {
datasets: [{
data: [Name,Email]
}],
// These labels appear in the legend and in the tooltips when hovering different arcs
labels: [Name, Email]
}
});
});
});
</script>
This is the output
According to the ChartJS documenation, the expected data passed for a pie chart is numbers only. Here's an example of a dataset that should work:
data = {
datasets: [{
data: [10, 20, 30]
}],
// These labels appear in the legend and in the tooltips when hovering different arcs
labels: [
'Red',
'Yellow',
'Blue'
]
};
Currently, your Ajax request is getting the name and email from the /users route; you will need to update the request to get some sort of number value from /users and add that to the dataset.
Related
I am plotting a number of highcharts dynamically in a loop and pushing each highchart to an array. So that while clicking on an external button, I can export the charts. But while pushing charts to array, only the last entry is properly set with options.
i had a reference to a fiddle that suggests to clone the options. [https://jsfiddle.net/ndb21y1w/][2]
https://www.highcharts.com/forum/viewtopic.php?t=38574
The fiddle have same series data plotted on all the charts. How to solve this if the data is different for each chart populated. Thanks for any help in advance.
Adding more clarity to question :
The data is populated dynamically in loop. My code logic is like:
counter i;
setInterval(function() {
//logic to populated data...
//It is a multiline chart, so three sets of arrays are populated.
//filling data1[], data2[] and data3[] .
drawChart(data1, data2, data3);
if(condition true) clearInterval();
i++;
});
drawChart(data1, data2, data3) {
var chart = new Highcharts.Chart({
title: {
text: "title",
},
xAxis: {
categories: [1,2,3,4...],
},
series: [{
type: 'line',
data: data1,
}, {
type: 'line',
data: data2,
}, {
type: 'line',
data: data3,
},
});
chartArray.push(chart);
}
This chartArray is where I mentioned to get the last entry only properly.
To create a chart you have to pass an HTML element that will be a chart container. In your code that what's missing. Check the demo I have prepared to reproduce this issue: https://jsfiddle.net/BlackLabel/c60y1t2v/
Code:
var chartArray = [],
counter = 1,
dataArr = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
],
containers = document.getElementById('containers');
function drawChart(data) {
var cnt = document.createElement('div'),
cntId = 'container' + counter++,
chart;
cnt.setAttribute('id', cntId);
containers.appendChild(cnt);
chart = new Highcharts.Chart(cntId, {
title: {
text: "title",
},
xAxis: {
categories: [1, 2, 3, 4],
},
series: [{
type: 'line',
data: data,
}]
});
return chart;
}
dataArr.forEach(function(data) {
var chart = drawChart(data);
chartArray.push(chart);
});
You need to define options each time you use a new chart. Reinitialize the OriginalOptions every time you create a new chart.
const options = [...Array(5)].map(() => {
const originalOptions = {
series: [{
data: [], // some random data
type: 'column'
}]
}
return Object.assign(originalOptions)
})
Fiddle
Updated:
For dynamically repopulating the chart, you have to initialize an empty chart and then add new series + redraw whenever your data is populated.
Your redraw function will look something like this:
var i = 0;
var data = [];
var chart = new Highcharts.Chart('container',{
series: []
});
var interval = setInterval(function() {
i++;
data[i] = [i*10 + 1, i*10+2, i*10+3];
drawChart(data[i]);
if(i > 2) clearInterval(interval);
},1000);
function drawChart(data) {
var series = {
type: 'line',
data: data
}
chart.addSeries(series, false);
chart.redraw();
}
See Updated Fiddle
To Print HTML as PDF you can use this software "wkhtmltopdf"
in Linux you need to use this command :
sudo apt-get install wkhtmltopdf
There are many library based on "wkhtmltopdf" in many languages so you can use it.
Library for PHP : https://github.com/mikehaertl/phpwkhtmltopdf
Store chart options in Array then map over to Initialize Highchart for each options.
var chartArray = [];
function drawChart(data1, data2, data3, i) {
// Create container for charts
const el = document.createElement('div');
document.body.appendChild(el).setAttribute("id", "container"+i);
// Create charts
var chart = new Highcharts.chart(el, {
series: [{
type: 'line',
data: data1,
}, {
type: 'line',
data: data2,
}, {
type: 'line',
data: data3,
}]
});
chartArray.push(chart);
console.log(chartArray);
}
var counter = 0;
var delayTime = 2000;
var timer = setInterval(function(){
var data1 = [30, 70, 50];
var data2 = [40, 70, 60];
var data3 = [10, 90, 20];
drawChart(data1, data2, data3, counter);
if(counter == 2){
clearInterval(timer);
}
counter++;
},delayTime);
<script src="https://code.highcharts.com/highcharts.js"></script>
I am trying to create a pie chart in JavaScript. I would like this chart to display in the legend only the labels that are non zero.
Does anyone have any ideas how this can be done?
Here is the code I have so far. Currently the legend of the pie chart shows all possible 12 Labels, even though 8 of these have zero value. "Data" will eventually be filled from a database and therefore it is important that this is an automated process.
var ctx = document.getElementById("myPieChart");
var myPieChart = new Chart(ctx, {
type: 'pie',
data: {
labels: ["Astronomica", "Deuteronic", "Floral", "Galactic","Celestrial","Heliosphere","Jupiter","Interstella","Koronis","Eclipse,"Borealis","Lunatic"],
datasets: [{
data: [12.21, 15.58, 11.25, 8.32],
backgroundColor: ['#007bff', '#dc3545', '#ffc107', '#28a745'],
}],
},
});
You can manage data before use they.
var ctx = document.getElementById("myPieChart");
var input_lables = ["Astronomica" , "Deuteronic", "Floral", "Galactic", "Celestrial", "Heliosphere", "Jupiter", "Interstella","Koronis", "Eclipse", "Borealis", "Lunatic"];
var input_values = [12.21, 15.58, 11.25, 8.32];
var output_lables = [];
var output_values = [];
for(var i=0;i<input_lables.length;i++){
if(!values[i]){
output_lables.push(input_lables[i]);
output_values.push(input_values[i]);
}
}
var myPieChart = new Chart(ctx, {
type: 'pie',
data: {
labels: output_lables,
datasets: [{
data: output_values,
backgroundColor: ['#007bff', '#dc3545', '#ffc107', '#28a745'],
}],
},
});
if you went to automatic it just enough make a function like this code.
According with the documentation you can use the filter parameter in the label
http://www.chartjs.org/docs/latest/configuration/legend.html
and you can make a validation to validate the data and if it is 0 you can return false
Filter a legend Item with Chartjs.org V2.7
I'm trying to plot a Chart using Google's Visualization API using some data returned from a database by a PHP script. My data is a JSON object in the format:
jsonObject = {
"routes":[{
"name":"Route 0",
"chart":{
"x":[ /* array of x values */ ],
"y":[ /* array of y values */ ]
}
},{
"name":"Route 1",
"chart":{
"x":[ /* array of x values */ ],
"y":[ /* array of y values */ ]
}
}]};
I'm trying to plot a chart of each member of jsonObject.routes individually using the following code:
function drawChart() {
var baseChart = jsonObject.routes[1].chart; // Want to manipulate this value to plot different sets of data
var chartData = [];
for (var g = 0; g < baseChart.x.length; g++) {
var dataPoint = {
c: [
{ v: baseChart.x[g] },
{ v: baseChart.y[g] },
]
};
chartData.push(dataPoint);
}
var dataJson = {
cols: [
{ role: "domain", type: "number", label: "Distance" },
{ role: "data", type: "number", label: "Main Route" },
],
rows: chartData
};
var dataTable = new google.visualization.DataTable(dataJson);
var chart = new google.visualization.AreaChart(document.getElementById('chart'));
var options = {};
chart.draw(dataTable, options);
}
However, whenever I try to access the latter objects of the jsonObject.route array, it seems to be pulling data for every object in the jsonObject.route array prior to it as well.
I've included a link to a Fiddle with a sample dataset at the bottom; the chart is fine when only plotting jsonObject.routes[0], but when trying to plot jsonObject.routes[1] it will plot the data from jsonObject.routes[0] too.
I suspect this is more of an issue with my Javascript code rather than with the Google Visualization API, but I've been pulling my hair out with it and can figure out why it's pulling data from all the elements in that array. Many thanks for any help!
Link to Fiddle
not sure i completely follow the question...
looking at the fiddle, the one chart seems to draw fine,
just need to sort the data to fix funny looking area
dataTable.sort([{column: 0}]);
see following snippet in order to draw separate charts for each --> jsonObject.routes
google.charts.load('current', {
callback: function () {
jsonObject.routes.forEach(function (route) {
var chartData = [];
route.chart.dist.forEach(function (x, index) {
chartData.push({
c: [
{v: x},
{v: route.chart.ele[index]}
]
});
});
var dataJson = {
cols: [
{ role: "domain", type: "number", label: "Distance" },
{ role: "data", type: "number", label: "Main Route" },
],
rows: chartData
};
var dataTable = new google.visualization.DataTable(dataJson);
dataTable.sort([{column: 0}]);
var options = {};
var container = document.getElementById('chart_div').appendChild(document.createElement('div'));
var chart = new google.visualization.AreaChart(container);
chart.draw(dataTable, options);
});
},
packages:['corechart']
});
note: definition of jsonObject is excluded above
AND
when building a working fiddle, i noticed that since jsonObject is so large,
once you leave the page and comeback,
the fiddle breaks it up into chunks, which then breaks the code
and only one chart is drawn
here is a working fiddle with far less data
I'm trying to show a Chart with Highcharts, using javascript.
I've read the csv file using Highcharts modules/data.js and the Chart is showing without problems inside my container.
mychart = Highcharts.chart('container', {
chart: {
type: 'scatter',
zoomType: 'xy'
},
data: {
csv: csv,
startColumn:0,
endColumn:2
},
title: {
text: 'DATA'
},
xAxis: {
title: {
text: 'X'
},
},
yAxis: {
title: {
text: 'Y'
}
}
});
Basically the csv have 3 columns, with commas separating attributes and break lines for each row.
x, y, category
data1, data2, data3
data1, data2, data3
data1, data2, data3
data1, data2, data3
data1, data2, data3
...
The first and the seconds columns are the points coordinates and the third is the category. I want to display points based on one of the categories in the third row.
I don't know how to show all x & y points categorized by category column.
You can think of a category as a series in Highcharts. So you need to create an array like this
series: [{
name: 'Series ' + categoryNumber,
data: [] // array with x and y coordinates
}, {
name: ''
data: []
}]
Then you can parse your csv file, it would be easier without data module.
var rows = csv.split('\n');
var series = [];
rows.forEach(row => {
var cells = row.split(',').map(Number);
var serie = series[cells[2]];
if (!serie) {
serie = series[cells[2]] = {data: []};
}
serie.data.push([cells[0], cells[1]]);
})
Highcharts.chart('container', {
chart: {
type: 'scatter'
},
series: series
});
example: http://jsfiddle.net/w7ug4dbw/
There is important for the chart series that you will not have gaps in your category - so if you have categories 0 - 2, you need to have data for all 0,1,2 category - if you don't, then you can receive the errors while using the chart. To overcome that, you would need to loop through the series array and delete all the gaps.
I am trying to plot a pie chart with data set containing zero values.But pie chart shows only labels till data gets updated.
What if I wanted to show empty pie chart.
I have given:
var data = [
{
label: "Series1",
data: 0,
url: "http://stackoverflow.com"},
{
label: "Series2",
data: 0,
url: "http://serverfault.com"},
{
label: "Serie3",
data: 0,
url: "http://superuser.com"},
{
label: "Series4",
data: 0,
url: "http://www.google.com"},
{
label: "Series5",
data: 0,
url: "http://www.oprah.com"},
{
label: "Series6",
data: 0,
url: "http://www.realultimatepower.net/"}
];
var options = {
series: {
pie: {
show: true
}
},
grid: {
hoverable: true
}
};
var plot = $.plot($("#graphLoaderDiv"), data, options);
Modify your label formatter function to return null if the series percent is zero.
After digging deeper I realized The best possible solution is to not to show pie chart if your data set values are zero.You either can do it editing following plugin or adding check inside your plotting function.
Download jquery.flot.pie.js from here
http://code.google.com/p/flot/issues/detail?id=530
Go to line No 411 and modify code as follows.
if( isNaN(angle) ) {
//var html = html = '<span class="pieLabel" id="pieLabelNoData" style="position:absolute;top:20px;left:5px;">There is no available data.</span>';
//html = target.append(html);
target.hide();
}
you can show empty data like this
$piedata="[{label:'no data',data:1}]";