how to assign dynamic value in canvasjs chart using angularjs - canvasjs

how to show dynamic data in canvasjs using angularjs. im getting data from api and want to display in chart. i don't know how to assign variable to the y points of chart.im getting the value and stored in the variable "ValueinCm" instead of static variable need to assign dynamic value.
<script src="http://canvasjs.com/assets/script/canvasjs.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script>
var filledValue;
var app = angular.module('myApp', ["ng-fusioncharts"])
app.controller('MyController', function ($scope, $http) {
$http.get('https://example.com', {
headers: { 'Authorization': 'Basic password==' }
})
.then(function (response) {
$scope.names = response.data;
$scope.decodedFrame = atob($scope.names.dataFrame);
$scope.decodedFrameNew = $scope.decodedFrame.substring(4);
$scope.distanceinFeet = $scope.decodedFrameNew * 12.5*2.54;
$scope.Value = $scope.distanceinFeet / 148;
$scope.ValueinCm = $scope.Value.toFixed(2);
filledValue = $scope.ValueinCm;
console.log(filledValue);
});
});
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer", {
theme: "theme2",//theme1
title: {
text: "Basic Column Chart - CanvasJS"
},
animationEnabled: false, // change to true
data: [
{
// Change type to "bar", "area", "spline", "pie",etc.
type: "column",
dataPoints: [
{ label: "apple", y: filledValue },
{ label: "orange", y: 15 },
{ label: "banana", y: 25 },
{ label: "mango", y: 30 },
{ label: "grape", y: 28 }
]
}
]
});
chart.render();
}
</script>
</head>
<body ng-app="myApp">
<div ng-controller="MyController">
<div id="chartContainer" style="height: 300px; width: 100%;"></div></div>
</body>

After fetching the data, you need to store it into a variable(say, data) which should be an array of objects. You need to make sure, this variable stores the data in CanvasJS prescribed format.
Later you can use this variable in place of your static data.
dataPoints: data
Here is a working jsFiddle

Related

how to fix this error Array to string conversion in laravel and chartjs?

i want to get sum men learning and women learning from learnings table and display to chart with group by province name.
Error:
Array to string conversion (View: C:\xampp\htdocs\project\resources\views\chart\index.blade.php)
my controller
$learnings =DB::table('provinces')
->join('learning_province','provinces.id','learning_province.province_id')
->join('learnings','learnings.id','learning_province.learning_id')
->select('title',\DB::raw('sum(men_learned + women_learned) as sum'))
->groupby('title')->whereYear('provinces.created_at', $year)->get();
$title = [];
$learning= [];
foreach ($learnings as $key => $value) {
$title[$key]=$value->title;
$learning[$key]=$value->sum;
}
return view('home.home', compact('learning', 'title'));
how to display sum men and women with group by province name in this script
my script
<script>
var ctx = document.getElementById('lineChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: [{!!$title!!}],
datasets: [{
label: '# ',
data: [{!!$learning!!}],
backgroundColor: ["#3e95cd"],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
</script>
However, instead of manually calling json_encode, you may use the #json Blade directive. The #json directive accepts the same arguments as PHP's json_encode function.
Please like this json_encode in laravel blade
<script>
var ctx = document.getElementById('lineChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: #json($title),
datasets: [{
label: '# ',
data: #json($learning),
backgroundColor: ["#3e95cd"],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
</script>

highcharts line graph with ajax

I would like to implement a simple line graph with ajax in which only two points
x will be the hours and y will be the count of calls.
CODE :
<script>
function getData() {
$.ajax({
type:'POST',
url: "http://localhost/demo_chart/test.php",
dataType: 'JSON',
success: function(response_data) {
new_data = $.map(response_data, function(i){
return {x: i['date'],y: i['count']};
});
$('#container').highcharts({
chart: {
renderTo: 'container',
type: 'line'
},
title: {
text: 'Count vs. Time'
},
xAxis: {
title: {
text: 'Time'
},
type: 'Time',
},
yAxis: {
title: {
text: 'Count'
}
},
series: [{
name: 'Test',
data: new_data
}]
});
}
})
}
$(document).ready(function () {
getData();
})
</script>
Output of http://localhost/demo_chart/test.php is same as below :
{"date":["13:00:00","13:00:01","13:00:02","13:00:03","13:00:04"],"count":["1","2","3","4","2"]}
But still graph is not generating. So i would like to know what is the problem here.
Anyone like to share some hint which can resolve this problem ?
Expected output is :
X- axis : show all date
Y-axis : show count
You need to correct your mapping function, for example:
var response = {
"date": ["13:00:00", "13:00:01", "13:00:02", "13:00:03", "13:00:04"],
"count": ["1", "2", "3", "4", "2"]
};
new_data = $.map(response.date, function(el, index) {
return {
name: el,
y: parseInt(response['count'][index])
};
});
Additionally, with that data structure, I recommend you to use category axis type.
xAxis: {
...,
type: 'category'
}
Live demo: http://jsfiddle.net/BlackLabel/ptx6fy2q/
API Reference: https://api.highcharts.com/highcharts/xAxis.type

I want to show the value of label inside the pie graph. (vue-chartjs / pieceLabel)

I am a student studying vue.
I used Vue-chartjs to draw a graph, and I'd like to display the value on a pie graph.
But I don't know what to do.
Please help me...
the current situation (image) : enter image description here
My wish (image) : enter image description here
Vue.component('pie-chart', {
extends : VueChartJs.Pie,
props: ['data', 'options'],
mounted(){
this.renderPieChart();
},
computed: {
attendanceData : function(){
return this.data
}
},
methods : {
renderPieChart : function(){
this.renderChart(
{
labels: ['a','b','c','d'],
datasets: [{
backgroundColor: ['#10a236', '#f9cd41', '#fe7272', '#5c7add'],
data: [10,20,30,40]
}]
},
{
responsive: true,
maintainAspectRatio: false,
pieceLabel: {
render: 'value',
precision: 1,
}
}
)
}
},
watch : {
attendanceData : function(){
this.$data._chart.destroy();
this.renderPieChart();
}
}
});
As The dicusstion on tooltip of chart.js at Stackoverflow, uses plugin is one solution.
then as Vue chart.js guide said,
in mounted(), uses this.addPlugin to add your plugin like below demo:
Vue.config.productionTip = false
//below plugin is copied from https://stackoverflow.com/a/37989832/5665870
let pluginConfig = {
id: 'my-plugin',
beforeRender: function (chart) {
if (chart.config.options.showAllTooltips) {
// create an array of tooltips
// we can't use the chart tooltip because there is only one tooltip per chart
chart.pluginTooltips = [];
chart.config.data.datasets.forEach(function (dataset, i) {
chart.getDatasetMeta(i).data.forEach(function (sector, j) {
chart.pluginTooltips.push(new Chart.Tooltip({
_chart: chart.chart,
_chartInstance: chart,
_data: chart.data,
_options: chart.options.tooltips,
_active: [sector]
}, chart));
});
});
// turn off normal tooltips
chart.options.tooltips.enabled = false;
}
},
afterDraw: function (chart, easing) {
if (chart.config.options.showAllTooltips) {
// we don't want the permanent tooltips to animate, so don't do anything till the animation runs atleast once
if (!chart.allTooltipsOnce) {
if (easing !== 1)
return;
chart.allTooltipsOnce = true;
}
// turn on tooltips
chart.options.tooltips.enabled = true;
Chart.helpers.each(chart.pluginTooltips, function (tooltip) {
tooltip.initialize();
tooltip.update();
// we don't actually need this since we are not animating tooltips
tooltip.pivot();
tooltip.transition(easing).draw();
});
chart.options.tooltips.enabled = false;
}
}
}
Vue.component('pie-chart', {
extends : VueChartJs.Pie,
props: ['data', 'options'],
mounted(){
this.addPlugin(pluginConfig);
this.renderPieChart();
},
computed: {
attendanceData : function(){
return this.data
}
},
methods : {
renderPieChart : function(){
this.renderChart(
{
labels: ['a','b','c','d'],
datasets: [{
backgroundColor: ['#10a236', '#f9cd41', '#fe7272', '#5c7add'],
data: [10,20,30,40]
}]
},
{
responsive: true,
maintainAspectRatio: false,
pieceLabel: {
render: 'value',
precision: 1
},
showAllTooltips: true
}
)
}
},
watch : {
attendanceData : function(){
//this.$data._chart.destroy();
//this.renderPieChart();
}
}
})
var vm = new Vue({
el: '#app',
data: {
message: 'Hello World'
}
})
<script src="https://unpkg.com/vue#2.5.16/dist/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.min.js"></script>
<script src="https://unpkg.com/vue-chartjs/dist/vue-chartjs.min.js"></script>
<div id="app">
<pie-chart></pie-chart>
</div>

I want to Pie chart animated at on load how I make it?(I am refer Google visualization API )

I refer animation tag in option
option:{
animation:
{
startup:true,
duration:1500,
easing:'out'
}
}
but it not working for my code, please suggest me any other method to make pie chart animate.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="//www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1', { packages: ['corechart'] });
google.setOnLoadCallback(drawChart);
</script>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: 'POST',
dataType: 'json',
contentType: 'application/json',
url: 'Dashboard.aspx/GetChartData',
data: '{}',
success:
function (response) {
drawChart(response.d);
}
});
})
function drawChart(dataValues) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'ColumnName');
data.addColumn('number', 'Value');
for (var i = 0; i < dataValues.length; i++) {
data.addRow([dataValues[i].ColumnName, dataValues[i].Value]);
}
var options = {
title: "All Complains Status",
position: "top",
fontsize: "14px",
is3D: true,
width: 700,
height: 400,
legend: { position: 'bottom' },
animation: {duration: 1000,easing: 'in',startup: true},
slices: { 0: { color: '#8e3333' }, 1: { color: '#af4e13' }, 2: { color: '#46416f' }, 3: { color: '#319bb9' }, 4: { color: '#305b63' }, 5: { color: '#34733f' }, 6: { color: '#222d32' } }
};
var chart = new google.visualization.PieChart(document.getElementById('chart_div'))
chart.draw(data, options);
// initial value
var percent = 0;
// start the animation loop
var handler = setInterval(function () {
// values increment
percent += 1;
// apply new values
data.setValue(0, 1, percent);
data.setValue(1, 1, 100 - percent);
// update the pie
chart.draw(data, options);
// check if we have reached the desired value
if (percent > 74)
// stop the loop
clearInterval(handler);
}, 20);
}
</script>

Chart Js Doughnut chart giving error

Before I was using chart.js version 1.0.
Now we have updated the js with vesion 2.4.0
But getting following error
var data = [
{
value: 20,
color: "cornflowerblue",
highlight: "lightskyblue",
label: "JavaScript"
},
{
value: 50,
color: "lightgreen",
highlight: "yellowgreen",
label: "HTML"
},
{
value: 40,
color: "orange",
highlight: "darkorange",
label: "CSS"
}
];
var options = { responsive: true };
var element = component.find('chart').getElement();
var ctx = element.getContext('2d');
var chart = new Chart(ctx).Doughnut(data);
======================
<div onclick="{!c.getChart}"> test
<canvas aura:id="chart" height="250" width="250"></canvas>
</div>
The syntax is different if you are using Chart.js v1 or v2.
And you said you imported the v2 library, but you are still using the v1 syntax with :
var chart = new Chart(ctx).Doughnut(data);
To fix this, you can change the syntax to the v2's :
var myChart = new Chart(ctx, {
type: 'doughnut',
data: data
});

Resources