This is my code format:How can I load data from angular scope object.
static data is working fine.But getting from scope object is displays nothing.
var app=angular.module('myApp',[])
app.controller('myController',function($scope){
$scope.init = function(){
$scope.loadData()
var ctx = document.getElementById('mycanvas').getContext('2d');
var chart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: ["EL", "AL", "PL", "CL"],
datasets: [{
backgroundColor: ['green', 'red', 'pink', 'blue'],
data: $scope.datas,
}]
},
options: {
legend: {
position: 'right',
labels: {
boxWidth: 12
}
},
tooltips: { bodyFontSize: 12 }
}
});
}
$scope.loadData = function(){
$scope.datas=[
{
'EL':2
},
{
'AL':2
},
{
'PL':2
},
{
'CL':2
}
]
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js"></script>
<div ng-app="myApp" ng-controller="myController" ng-init="init()">
<canvas id="mycanvas"></canvas>
</div>
How can I load data from angular scope object for chart.
You almost did it right!
The point here is your data format.
You can't pass objects like this.
$scope.requestedLeaveTypeCount=[{'EL': 2}, {'AL': 2}, {'PL': 2}, {'CL': 2}];
This kind of data format is working.
$scope.requestedLeaveTypeCount=[2,2,2,2]
DEMO
Related
I am using chart.js for my project. As you can see in the following code, chart.js uses different minimum and maximum values for y-axis for line and bar graphs for same data. In the given code, 1100-1700 is the value range for line graph whereas 0-2000 is the value range used for bar graph.
I like to make same minimum and maximum values for both line and bar graphs. One option is to find minimum, maximum and step-size values my own and use the properties min, max and ticks.stepSize under scales. But finding minimum, maximum and step-size for a given data data is a serious task.
For my requirement, default minimum ,maximum and stepSize used by chart.js for line graph is fine and I would like to use the same values for bar graph also.
I could first render line graph, get these values from this graph (like scales.y.min) and then use it for bar graph, which is perfectly working
Is there a way I could get the default min, max, stepSize values used by chart.js for line graph before actually drawing the graph? Any answers or pointers are really appreciated. Thanks
var chart1 = new Chart(document.getElementById('chart1'),
{
type: 'line',
data:
{
labels: ['a','b','c'],
datasets:
[
{
label: 'A',
data: [1212,1122, 1188, 1617, 1116],
borderColor: 'green',
}
]
}
});
var chart2 = new Chart(document.getElementById('chart2'),
{
type: 'bar',
data:
{
labels: ['a','b','c'],
datasets:
[
{
label: 'A',
data: [1212,1122, 1188, 1617, 1116],
backgroundColor: 'green',
}
]
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.min.js"></script>
<div style="width:300px;height:200px"><canvas id="chart1"></canvas></div>
<div style="width:300px;height:200px"><canvas id="chart2"></canvas></div>
The first thing you could do is to set beginAtZero to false to Y axis of bar chart because is set to true by default:
https://github.com/chartjs/Chart.js/blob/v3.9.1/src/controllers/controller.bar.js#L636-L650
Then you can set the same scale config to both charts.
options: { // options of charts
scales: {
y: {
beginAtZero: false,
}
}
}
var chart1 = new Chart(document.getElementById('myChart1'),
{
type: 'line',
data:
{
labels: ['a','b','c'],
datasets:
[
{
label: 'A',
data: [1212,1122, 1188, 1617, 1116],
borderColor: 'green',
}
]
},
options: {
scales: {
y: {
beginAtZero: false,
}
}
}
});
var chart2 = new Chart(document.getElementById('myChart2'),
{
type: 'bar',
data:
{
labels: ['a','b','c'],
datasets:
[
{
label: 'A',
data: [1212,1122, 1188, 1617, 1116],
backgroundColor: 'green',
}
]
},
options: {
scales: {
y: {
beginAtZero: false,
}
}
}
});
.myChartDiv {
max-width: 300px;
max-height: 200px;
}
<script src="https://cdn.jsdelivr.net/npm/chart.js#3.9.1/dist/chart.min.js"></script>
<html>
<body>
<div class="myChartDiv">
<canvas id="myChart1" width="300" height="200"/>
</div>
<div class="myChartDiv">
<canvas id="myChart2" width="300" height="200"/>
</div>
</body>
</html>
I have some python code which sucessfully passes two array to my html template
#app.route('/line')
def line():
df= av_query(av_start_date,av_end_date,'44201')
df['dt']=pd.to_datetime(df['Date'])
df['RawValue']=np.where(df['Units']=='007',df['RawValue']*1000,df['RawValue'] )
temp_df=df[df['Site']=='SM']
dates = temp_df['dt']
values = temp_df['RawValue']
return render_template('line.html', title='Ozone Data',dates=dates[:5], values=values[:5], max_n=100)
and in my html template I have tested this plotting code
<center>
<h1>{{ title }}</h1>
<canvas id="myChart" width="600" height="400"></canvas>
<script>
var s1 = {
label: 's1',
borderColor: 'blue',
data: [
{ x: '2017-01-06 18:39:30', y: 100 },
{ x: '2017-01-07 18:39:28', y: 101 },
]
};
var s2 = {
label: 's2',
borderColor: 'red',
data: [
{ x: '2017-01-07 18:00:00', y: 90 },
{ x: '2017-01-08 18:00:00', y: 105 },
]
};
var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
type: 'line',
data: { datasets: [s1, s2] },
options: {
scales: {
xAxes: [{
type: 'time'
}]
}
}
});
</script>
</center>
How do I replace the dummy data in s1 and s2 with my data?
I tried to push each line to the dataset but that did not seem work.
var s1 = {
label: 's1',
borderColor: 'blue',
dates=dates
values=values
data: []
for (i=0; i<=dates.length; i++){
data.push({x:dates[i], y:values[i]})
}
};
I found the easiest way to do this is render a variable in the page using the template.
If your data is in an array or dictionary, make sure to convert it to json before passing it to the template, then pass it to the javascript when the template renders like so:
<script>
const data = {{ data|safe }};
</script>
JSON will natively render as Javascript and you can do with it what you will then.
Make sure you pass it through the safe filter or it will just be escaped.
I want to that the Chart start at 0. But it takes always the lower value to start.
I already tried a few things but nothing works.
It never takes the settings done in de options Part of de javascript part. So i dont know what the issue is. It never starts at 0. But this is what i want to.
Please help. Thank you very much :)
Looks currently like this: https://school.luis-luescher.com/m242/moin/index.php
<!DOCTYPE html>
<html>
<head>
<title>Database</title>
<style type="text/css">
BODY {
width: 550PX;
}
#chart-container {
width: 100%;
height: auto;
}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.9.4/dist/Chart.min.js"></script>
</head>
<body>
<div id="chart-container">
<canvas id="graphCanvas"></canvas>
</div>
<script>
$(document).ready(function() {
showGraph();
});
function showGraph() {
{
$.post("https://school.luis-luescher.com/m242/moin/data.php",
function(data) {
console.log(data);
var trytime = [];
var count = [];
for (var i in data) {
trytime.push(data[i].trytime);
count.push(data[i].count);
}
var chartdata = {
labels: trytime,
datasets: [{
label: 'Erfolgreiche Authentifizerungen',
backgroundColor: '#8846f1',
borderColor: '#a446f1',
hoverBackgroundColor: '#CCCCCC',
hoverBorderColor: '#666666',
borderWidth: 1,
data: count,
}],
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
}
var graphTarget = $("#graphCanvas");
var barGraph = new Chart(graphTarget, {
type: 'bar',
data: chartdata
});
});
}
}
</script>
</body>
</html>
Your Options object must be outside chartData.
var barGraph = new Chart(graphTarget, {
type: 'bar',
data: chartdata,
options: options
});
I am having an scenario, where I need to show the slice value inside of the slice in pie chart. I am having more than 1 pie charts on my webpage. Below code is perfectly working but only for 1st Pie Chart and for others its throwing error as below, could you please help me to sort this out?
Error:: unCaught TypeError: cannot read the property 'data' of undefined.
Code::
options:{
animation:{
onComplete:function(){
var ctx = this.chart.ctx;
var dataset_obj = this.data.datasets;
for (var i=0;i<dataset_obj.length; i++){
var meta_obj = dataset_obj[i]._meta[i].data;
for (var j=0; j<meta_obj.length; j++){
var model =meta_obj[j]._model;
start_angle= model.startAngle;
end_angle = model.endAngle;
mid_angle =start_angle + ( end_angle -start_angle)/2;
mid_radius = model.innerRadius + (model.outerRadius -model.innerRadius)/2;
var x =mid_radius*math.cos(mid_angle);
var y = mid_radius*math.cos(mid_angle);
ctx.fillstyle='#fff';
if (dataset_obj[i].data[j] != 0 && meta_obj[j].hidden != true){
ctx.fillText(dataset_obj[i].data[j], model.x+x, model.y+y);
}
}
}
}
}
}
This answers the issue contained in the question's title:
How to show slice value inside of slice in pie chart using chart.js
The code snippet below show how to display the values inside the slices with the use of chartjs-plugin-labels. The code of the samples was extracted from the chartjs-plugin-labels demo page.
var canvas = document.getElementById('myChart');
new Chart(canvas, {
type: 'pie',
data: {
labels: ['January', 'February', 'March'],
datasets: [{
data: [50445, 33655, 15900],
backgroundColor: ['#FF6384', '#36A2EB','#FFCE56']
}]
},
options: {
responsive: true,
maintainAspectRatio: true,
plugins: {
labels: {
render: 'value',
fontColor: ['green', 'white', 'red']
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/emn178/chartjs-plugin-labels/src/chartjs-plugin-labels.js"></script>
<canvas id="myChart"></canvas>
If you want to display the percentage of each slice, you can do the following:
var canvas = document.getElementById('myChart');
new Chart(canvas, {
type: 'pie',
data: {
labels: ['January', 'February', 'March'],
datasets: [{
data: [50445, 33655, 15900],
backgroundColor: ['#FF6384', '#36A2EB','#FFCE56']
}]
},
options: {
responsive: true,
maintainAspectRatio: true,
plugins: {
labels: {
render: 'percentage',
fontColor: ['green', 'white', 'red'],
precision: 2
}
},
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/emn178/chartjs-plugin-labels/src/chartjs-plugin-labels.js"></script>
<canvas id="myChart"></canvas>
Just wondering if there is any way to set the horizontal bar labels for y-axis using chart.js. Here is how I set up the chart:
<div class="box-body">
<canvas id="chart" style="position: relative; height: 300px;"></canvas>
</div>
Javascript:
var ctx = document.getElementById('chart').getContext("2d");
var options = {
layout: {
padding: {
top: 5,
}
},
responsive: true,
animation: {
animateScale: true,
animateRotate: true
},
};
var opt = {
type: "horizontalBar",
data: {
labels: label,
datasets: [{
data: price,
}]
},
options: options
};
if (chart) chart.destroy();
chart= new Chart(ctx, opt);
chart.update();
As you all can see, the first and third labels are too long and cut off. Is there a way to make the label multi-line?
If you want to have full control over how long labels are broken down across lines you can specify the breaking point by providing labels in a nested array. For example:
var chart = new Chart(ctx, {
...
data: {
labels: [["Label1 Line1:","Label1 Line2"],["Label2 Line1","Label2 Line2"]],
datasets: [{
...
});
You can use the following chart plugin :
plugins: [{
beforeInit: function(chart) {
chart.data.labels.forEach(function(e, i, a) {
if (/\n/.test(e)) {
a[i] = e.split(/\n/);
}
});
}
}]
add this followed by your chart options
ᴜꜱᴀɢᴇ :
add a new line character (\n) to your label, wherever you wish to add a line break.
ᴅᴇᴍᴏ
var chart = new Chart(ctx, {
type: 'horizontalBar',
data: {
labels: ['Jan\n2017', 'Feb', 'Mar', 'Apr'],
datasets: [{
label: 'BAR',
data: [1, 2, 3, 4],
backgroundColor: 'rgba(0, 119, 290, 0.7)'
}]
},
options: {
scales: {
xAxes: [{
ticks: {
beginAtZero: true
}
}]
}
},
plugins: [{
beforeInit: function(chart) {
chart.data.labels.forEach(function(e, i, a) {
if (/\n/.test(e)) {
a[i] = e.split(/\n/);
}
});
}
}]
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="ctx"></canvas>