Related
I have complication in pushing the data that i have compute in typescript component into my chart.js code. when I check it in web interface with the chart.js the data do appear.
the data appear in the web view
code I use to call the data in web view
but when I use this.october (i.e) into the chart.js code. it didnt appear.
this is the code I used to subscribe and count the data
.subscribe((dataChart) => {
for (const e of dataChart) {
var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
var str=e.strRequestDate; //Set the string in the proper format(best to use ISO format ie YYYY-MM-DD or YYYY-MM-DDTHH:MM:SS)
var d=new Date(str); //converts the string into date object
// console.log(d)
var m=d.getMonth(); //get the value of month
//console.log(monthNames[m]) // Print the month name
if (monthNames[m] === "January"){
this.January++
}
if (monthNames[m] === "February"){
this.February++
}
if (monthNames[m] === "March"){
this.March++
}
if (monthNames[m] === "April"){
this.April++
}
if (monthNames[m] === "May"){
this.May++
}
if (monthNames[m] === "June"){
this.June++
}
if (monthNames[m] === "July"){
this.July++
}
if (monthNames[m] === "August"){
this.August++
}
if (monthNames[m] === "September"){
this.September++
}
if (monthNames[m] === "October"){
this.October++
}
if (monthNames[m] === "November"){
this.November++
}
if (monthNames[m] === "December"){
this.December++
}
}
// console.log(this.January) //checking if the value properly generated
},
(error) => {
console.error(error);
}
);
}
this is the code for chart.js within the same component with API that I count.
ngOnInit() {
var myChart = new Chart("myChart", {
type: 'line',
data: {
//labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
labels: ['October', 'November', 'December', 'January', 'February', 'March'],
datasets: [{
label: 'Monthly Record of IT SIR Request',
data: [this.October, this.November, this.December, this.January, this.February, this.March], <== this data return 0 in the chart
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)',
'rgba(153, 0, 153, 0.2)',
'rgba(102, 255, 153, 0.2)',
'rgba(255, 51, 0, 0.2)',
'rgba(204, 0, 204, 0.2)',
'rgba(0, 0, 255, 0.2)',
'rgba(0, 153, 153, 0.2)'
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)',
'rgba(153, 0, 153, 1)',
'rgba(102, 255, 153, 1)',
'rgba(255, 51, 0, 1)',
'rgba(204, 0, 204, 1)',
'rgba(0, 0, 255, 1)',
'rgba(0, 153, 153, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
})
}
lastly this is the error that i screenshot
All returning 0 as value
I found an answer. i need to write the code within the subscribe in order for me to reuse the data that i have manipulate for the chart.js
this is the answer on how to make it work:
.subscribe((dataChart) => {
for (const e of dataChart) {
var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
var str=e.strRequestDate; //Set the string in the proper format(best to use ISO format ie YYYY-MM-DD or YYYY-MM-DDTHH:MM:SS)
var d=new Date(str); //converts the string into date object
// console.log(d)
var m=d.getMonth(); //get the value of month
//console.log(monthNames[m]) // Print the month name
if (monthNames[m] === "January"){
this.January++
}
if (monthNames[m] === "February"){
this.February++
}
if (monthNames[m] === "March"){
this.March++
}
if (monthNames[m] === "April"){
this.April++
}
if (monthNames[m] === "May"){
this.May++
}
if (monthNames[m] === "June"){
this.June++
}
if (monthNames[m] === "July"){
this.July++
}
if (monthNames[m] === "August"){
this.August++
}
if (monthNames[m] === "September"){
this.September++
}
if (monthNames[m] === "October"){
this.October++
}
if (monthNames[m] === "November"){
this.November++
}
if (monthNames[m] === "December"){
this.December++
}
}
var myChart = new Chart("myChart", {
type: 'line',
data: {
labels: ['October 2020', 'November 2020', 'December 2020', 'January 2021', 'February 2021', 'March 2021'],
datasets: [{
label: 'Monthly Record of IT SIR Request',
data: [this.October, this.November, this.December, this.January, this.February, this.March],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)',
'rgba(153, 0, 153, 0.2)',
'rgba(102, 255, 153, 0.2)',
'rgba(255, 51, 0, 0.2)',
'rgba(204, 0, 204, 0.2)',
'rgba(0, 0, 255, 0.2)',
'rgba(0, 153, 153, 0.2)'
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)',
'rgba(153, 0, 153, 1)',
'rgba(102, 255, 153, 1)',
'rgba(255, 51, 0, 1)',
'rgba(204, 0, 204, 1)',
'rgba(0, 0, 255, 1)',
'rgba(0, 153, 153, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
})
},
I am using Angular & Chart.js (with ng2-charts) on my an app.
With bar chart, by default, when I clicking on a column I get a tooltip as shown :
I want to change the inside of that tooltip. This is my code :
my-bar-chart.component.html :
<div class="container chart-style">
<canvas baseChart
[datasets]="barChartData"
[labels]="barChartLabels"
[options]="barChartOptions"
[legend]="barChartLegend"
[chartType]="barChartType"
[options]="barChartTooltip"
style="height:20rem; width:100rem"
>
</canvas>
</div>
and my-bar-chart.component.ts :
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-my-bar-chart',
templateUrl: './my-bar-chart.component.html',
styleUrls: ['./my-bar-chart.component.css']
})
export class MyBarChartComponent {
constructor() { }
public barChartOptions = {
scaleShowVerticalLines: true,
responsive: true,
maintainAspectRatio: false
};
public barChartLabels = ['One star', 'Two stars', 'Three stars', 'four stars', 'Five stars'];
public barChartType = 'bar';
public barChartLegend = true;
public barChartData = [
{data: [28, 39, 42, 19, 8],
label: 'amount',
backgroundColor: [
'rgba(54, 162, 235, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(54, 162, 235, 0.2)',
],
borderWidth: 0,
hoverBackgroundColor: 'rgba(221, 221, 221, 1)',
scaleStepWidth: 1,
pointHoverBorderColor: 'rgba(255,1,2, 1)',
}
];
public barChartTooltip = //I dont know
}
I'm following this article to render highchart with json data from django query. However chart is not rendered but I'm not getting any errors from Django or by the client when inspecting source. Appreciate if anyone can point the mistakes. Thank you in advance.
I'm using django 2.0 and python3.5
models.py
PLATFORM = (
('ipcore','IPCORE'),
('metro','METRO E'),
('edge','EDGE'),
('access','ACCESS'),
('voice','VOICE'),
('system','SYSTEM'),
('iptv','IPTV'))
class Contract(models.Model):
vendor_name = models.ForeignKey(Vendor, on_delete=models.CASCADE)
name = models.CharField(max_length=500)
contract_no = models.CharField(max_length=100, blank=True)
partner_name = models.CharField(max_length=200, blank=True)
value = models.DecimalField(max_digits=11, decimal_places=2,
blank=True, null=True)
platform = models.CharField(max_length=100, blank=True,
choices=PLATFORM)
views.py
def json_example(request):
return render(request, 'app/json_example.html')
def chart_data(request):
dataset=Contract.objects.all().values('platform').
exclude(platform='').annotate(Sum('value')).order_by('value__sum')
platform_name = dict()
for platform_tuple in Contract.PLATFORM:
platform_name[platform_tuple[0]] = platform_tuple[1]
chart = {
'chart': {'type': 'pie'},
'title': {'text': 'Contract Value for Every platform'},
'series': [{
'name': 'Platform',
'data': list(map(lambda row: {'name':
platform_name[row['platform']],
'y': row['value__sum']}, dataset))
}]
}
return JsonResponse(chart)
urls.py
url('json_example/', views.json_example, name='json_example'),
url('json_example/data/', views.chart_data, name='chart_data'),
json_example.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Contract Inventory Highcharts Example</title>
</head>
<body>
<div id="container" data-url="{% url 'chart_data' %}"></div>
<script src="https://code.highcharts.com/highcharts.src.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
$.ajax({
url: $("#container").attr("data-url"),
dataType: 'json',
success: function (data) {
Highcharts.chart("container", data);
}
});
</script>
</body>
</html>
This is the json data from dataset.
[{"platform": "IPTV", "value__sum": "0.00"}, {"platform": "METRO E", "value__sum": "71372564.20"}, {"platform": "EDGE", "value__sum": "73867073.63"}, {"platform": "SYSTEM", "value__sum": "135465418.85"}, {"platform": "IPCORE", "value__sum": "467810178.41"}]
This is the json data from dataset.
[{"platform": "IPTV", "value__sum": "0.00"}, {"platform": "METRO E", "value__sum": "71372564.20"}, {"platform": "EDGE", "value__sum": "73867073.63"}, {"platform": "SYSTEM", "value__sum": "135465418.85"}, {"platform": "IPCORE", "value__sum": "467810178.41"}]
Your json data doesn't contain chart options. It should be something like this:
'{"title":{"text":"Title"},"series":[{"name":"Installation","data":[43934,52503,57177,69658,97031,119931,137133,154175]}]}'
What's more, you should parse json to js object before passing it to Highcharts constructor:
<script>
$.ajax({
url: $("#container").attr("data-url"),
dataType: 'json',
success: function (data) {
var chartData = JSON.parse(data);
Highcharts.chart("container", chartData);
}
});
</script>
Check the example:
https://jsfiddle.net/BlackLabel/7zfyhnbr/
You have to format the data in such a way that it should match the highcharts ploting object. Please checkout the below code.
data = [
{"platform": "IPTV", "value__sum": "0.00"},
{"platform": "METRO E", "value__sum": "71372564.20"},
{"platform": "EDGE", "value__sum": "73867073.63"},
{"platform": "SYSTEM", "value__sum": "135465418.85"},
{"platform": "IPCORE", "value__sum": "467810178.41"}];
x_axis_data = [];
y_axis_data = [];
for(index=0; index < data.length; index++) {
item = data[index];
x_axis_data.push(item['platform'])
y_axis_data.push(parseFloat(item['value__sum']))
}
Highcharts.chart('container', {
title: {
text: 'learnbatta.com'
},
xAxis: {
title: {
text: 'X Value'
},
categories: x_axis_data
},
yAxis: {
title: {
text: 'Y Value'
},
},
series: [{
name: 'Curve',
data: y_axis_data
}]
});
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div id="container"></div>
</body>
</html>
You have to update your code like below
<script>
$.ajax({
url: $("#container").attr("data-url"),
dataType: 'json',
success: function (data) {
var data = JSON.parse(data);
x_axis_data = [];
y_axis_data = [];
for(index=0; index < data.length; index++) {
item = data[index];
x_axis_data.push(item['platform'])
y_axis_data.push(parseFloat(item['value__sum']))
}
Highcharts.chart('container', {
title: {
text: 'learnbatta.com'
},
xAxis: {
title: {
text: 'X Value'
},
categories: x_axis_data
},
yAxis: {
title: {
text: 'Y Value'
},
},
series: [{
name: 'Curve',
data: y_axis_data
}]
});
}
});
</script>
I've manage to solve it by updated my views.py using django rest API and my template accordingly. Here is my updated code:
views.py
from rest_framework.views import APIView
from rest_framework.response import Response
class ChartView(View):
def get(self, request, *args, **kwargs):
return render(request, 'app/charts.html')
class ChartData(APIView):
authentication_classes = []
permission_classes = []
def get(self, request, format=None):
totalvendor= Contract.objects.all().values("vendor_name_id__name").
annotate(Count("id")).order_by('-id__count')[:8]
labels = totalvendor.values_list('vendor_name_id__name')
default_items = totalvendor.values_list('id__count', flat=True)
default_items = list(default_items)
data = {
"labels": labels,
"default": default_items,
}
return Response(data)
Pass an array from queryset to template and js
Here is my urls.py
url(r'^chart/', views.ChartView.as_view(), name='chart'),
url(r'^api/chart/data/$', ChartData.as_view(), name='chartdata'),
Here my code for charts.html
<script>
{% block jquery %}
var endpoint = '/api/chart/data/'
var defaultData = []
var labels = [];
$.ajax({
method: "GET",
url: endpoint,
success: function(data){
labels = data.labels
defaultData = data.default
setChart()
},
error: function(error_data){
console.log("error")
console.log(error_data)
}
})
function setChart(){
var ctx = document.getElementById("myChart");
var ctx2 = document.getElementById("myChart2");
var myChart = new Chart(ctx2, {
type: 'bar',
data: {
labels: labels,
datasets: [{
label: 'Value Contract for Platform',
data: defaultData,
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
title:{
display:true,
text:'Count Contract for Every Platform',
fontSize:18,
position:'top'
},
legend:{
display:false,
position:'right',
labels:{
fontColor:'#000'
}
},
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
var myChart = new Chart(ctx, {
type: 'polarArea',
data: {
labels: labels,
datasets: [{
label: 'Count Contract for Platform',
data: defaultData,
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
}
// var ctx = document.getElementById("myChart");
{% endblock %}
</script>
{% block content %}
<div class='row'>
<div class='col-sm-12' url-endpoint='{% url "chartdata" %}'>
<h1>Data Presentation</h1>
<div class=''>
<div class='col-sm-6'>
<canvas id="myChart" width="400" height="400"></canvas>
</div>
<div class='col-sm-6'>
<canvas id="myChart2" width="400" height="400"></canvas>
</div>
</div>
</div>
</div>
{% endblock content %}
Anyway thanks to those who answered my questions
I just started my adventure with chartsjs. I tried to modify all tutorials I found to suit my needs, but unfortunately the page doesn't display the chart and doesn't give any errors. Can anyone advice please.
$result='';
$sql="SELECT Q1.uUserName AS Technician, sum(if(Q2.dCatFK=1,1,0)) AS AM, sum(if(Q2.dCatFK=2,1,0)) as PM
FROM T_users as Q1 LEFT JOIN (SELECT dUser2FK, dCatFK FROM T_Defects
INNER JOIN T_settings WHERE (dDateClosed >= FYDateFROM AND dDateClosed <= FYDateTO)";
if (!empty($_SESSION['dept'])) { $sql .= ' AND dDeptFK = '.$_SESSION['dept'];}
if (!empty($_SESSION['area'])) { $sql .= ' AND dAreaFK = '.$_SESSION['area'];}
if (!empty($_SESSION['month'])){ $sql .= ' AND MONTH(dDateClosed) = '.$_SESSION['month'];}
$sql .=") as Q2 ON Q1.uPK = Q2.dUser2FK GROUP BY Q1.uUserName ORDER BY sum(if(dCatFK is not null,1,0)) DESC, Q1.uUsername;";
try{
$stmt = $con->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$label = array();
$data = array();
foreach ($result as $row) {
$label[] = $row["Technician"];
$data[] = $row["AM"];
$data[] = $row['PM'];
}
} catch(PDOException $e){
echo 'ERROR: ' . $e->getMessage();
}
<canvas id="myChart_Fixed" width="1000" height="400"></canvas>
<script>
var randomScalingFactor = function(){ return Math.round(Math.random()*100)};
var ctx = document.getElementById("myChart_Fixed");
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels:<?=json_encode($label);?>,
datasets: [{
label: 'Fixed AM',
data:<?=json_encode(array_values($data[0]));?>,
backgroundColor: 'rgba(54, 162, 235, 0.2)',
borderColor: 'rgba(54, 162, 235, 1)',
borderWidth: 1
},
{
label: 'Fixed PM',
data:<?=json_encode(array_values($data[1]));?>,
backgroundColor: 'rgba(255, 99, 132, 0.2)',
borderColor: 'rgba(255,99,132,1)',
borderWidth: 1
}
]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
</script>
you're appending your $data with AM and PM data so there are no 2 datasets instead there is only one dataset. Because of that $data[1] doesn't exists. Declare another 2 arrays and insert there your data for AM and PM respectively, then insert $dataAM at $data[0]... Let the code speak for itself:
...PHP file
$data = array();
$dataAM = array();
$dataPM = array();
foreach ($result as $row) {
$label[] = $row["Technician"];
$dataAM[] = $row["AM"];
$dataPM[] .=$row['PM'];
}
$data[0] = $dataAM;
$data[1] = $dataPM;
...HTML File
data: {
labels:<?=json_encode($label);?>,
datasets: [{
label: 'Fixed AM',
data:<?=json_encode(array_values($data[0]));?>,
backgroundColor: 'rgba(54, 162, 235, 0.2)',
borderColor: 'rgba(54, 162, 235, 1)',
borderWidth: 1
},
{
label: 'Fixed PM',
data:<?=json_encode(array_values($data[1]));?>,
backgroundColor: 'rgba(255, 99, 132, 0.2)',
borderColor: 'rgba(255,99,132,1)',
borderWidth: 1
}
]
},
Typo error, changed this:
json_encode(array_values($data[0]))
to this:
json_encode(array_values($data))
I'm using Laravel elixir to compile my js and css files with gulp. I'm using Chrome to debug, and it's picking up the sourcemaps generated by mix.styles and mix.scripts but not the one generated by mix.browserify. I can't see what I'm doing wrong. I want it to tell me that I have an error on custom-charts.js at line 45 of the source file but instead it says it is on line 14785 of the compiled file.
Here is my gulpfile:
var elixir = require('laravel-elixir');
elixir(function(mix) {
mix.less('app.less', 'resources/assets/css')
.styles([
'libs/jquery-ui.min.css',
'libs/jquery-ui.structure.min.css',
'libs/jquery-ui.theme.min.css',
'libs/select2.min.css',
'app.css'
])
.browserify('custom-charts.js')
.scripts([
'libs/jquery.min.js',
'libs/bootstrap.min.js',
'libs/select2.min.js',
'libs/jquery-ui.min.js',
'libs/vue.js',
'plugin-options.js',
'custom-jquery.js',
'custom-vue.js',
]);
});
Here is custom-charts.js:
import Chart from 'chart.js';
var ctx = document.getElementById("graph").getContext("2d");
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
new Vue({
el: 'body',
components: { Graph }
});
It does produce a custom-charts.js.map file, and the compiled scripts does say this at the end: //# sourceMappingURL=custom-charts.js.map. Chrome is just not reading it.
Hope this might help a bit
The browserify function as mention in the documentation
elixir(function(mix) {
mix.browserify('index.js');
});
assumes that your scripts are stored in resources/assets/js, though you're free to override the default.
Alternatively you might want to use laravel-elixir-browserify here
npm install --save-dev laravel-elixir-browserify
and include in the gulpfile.js as
var browserify = require('laravel-elixir-browserify');