Highcharts with json from django query not rendered - json

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

Related

How to reset chart.js chart yAxes count on tab change in angular?

I am using chart.js in Angular for display data.
Is there any way to reset yAxes data on change tab?
Here's a link for Stackblitz demo.
On load I am getting data like this.
Than if i change tab than data are coming perfectly like below image.
But when I change tab again to first tab at that time data is coming perfect but yAxes data is not changing therefore my chart is looks deferent from initial load. like below image.
HTML CODE
<mat-tab-group #tabgroup2 class="chart-filter-list" (selectedTabChange)="onTabChanged($event);">
<mat-tab label="{{'This Week' | translate}}"></mat-tab>
<mat-tab label="{{'This Month' | translate}}"></mat-tab>
<mat-tab label="{{'This Year' | translate}}"></mat-tab>
</mat-tab-group>
<div class="chart-body">
<canvas baseChart
[datasets]="recruitingChartData"
[labels]="recruitingChartLabels"
[options]="recruitingChartOptions"
[legend]="recruitingChartLegend"
[plugins]="recruitingChartPlugins"
[colors]="recruitingChartColors"
[chartType]="recruitingChartType">
</canvas>
</div>
ts file code
onTabChanged($event) {
const eventLabel = $event.tab.textLabel
if (eventLabel == 'This Year'){
this.tabSelectValue = 'yearly'
}else if (eventLabel == 'This Month'){
this.tabSelectValue = 'monthly'
}else {
this.tabSelectValue = 'weekly'
}
this.getDashboardMainData({});
}
// Recruiting Chart
public recruitingChartGetData : any = [];
public recruitingOpeningData : any = [];
public recruitingCandidateData : any = [];
public recruitingApplicationData : any = [];
public recruitingChartData: any = [
{ data: [ ], label: this.translate.instant('Job Openings') },
{ data: [ ], label: this.translate.instant('Candidates') },
{ data: [ ], label: this.translate.instant('Job Applications') },
];
public recruitingChartColors: any = [
{ // grey
backgroundColor: 'rgba(255, 99, 71, 0)',
borderColor: '#262f79',
pointBackgroundColor: 'rgba(148,159,177,1)',
pointBorderColor: '#fff',
pointHoverBackgroundColor: '#fff',
pointHoverBorderColor: 'rgba(148,159,177,0.8)'
},
{ // Blue
backgroundColor: 'rgba(255, 99, 71, 0)',
borderColor: '#fdb167',
pointBackgroundColor: 'rgba(148,159,177,1)',
pointBorderColor: '#fff',
pointHoverBackgroundColor: '#fff',
pointHoverBorderColor: 'rgba(148,159,177,0.8)'
},
{ // red
backgroundColor: 'rgba(255, 99, 71, 0)',
borderColor: '#30c76f',
pointBackgroundColor: 'rgba(148,159,177,1)',
pointBorderColor: '#fff',
pointHoverBackgroundColor: '#fff',
pointHoverBorderColor: 'rgba(148,159,177,0.8)'
}
];
public recruitingChartLabels: any = [];
public recruitingChartOptions = {
responsive: true,
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
},
};
public recruitingChartLegend = false;
public recruitingChartType: any = 'line';
public recruitingChartPlugins = [];
You need to also re-initialize recruitingChartData each time a new tab is selected. This can be done inside getDashboardMainData as follows.
async getDashboardMainData(request): Promise<void> {
...
this.recruitingChartData.forEach(o => o.data = []);
Please take a look at your amended StackBlitz and see how it works.

get the count of dayname Failed - Laravel 9

For my case , I have a data table contains a timestamps data call "created_at" , right now , it want to get the count of the dayname of the time stamp
so ideally it will be like
and I like to save it on the array for me to pass the data to may chart.js chart
so what i do is
$getdate = DB::table('watchlists')
->select('created_at')
->get();
$getweekday = Carbon::parse($getdate)->format('l');
$dayarray=[];
if($getweekday =='Monday')
{
$mondaycount = Carbon::parse($getdate)->count();
$dayarray=[0];
}
elseif($getweekday =='Tuesday')
{
$tuesday = Carbon::parse($getdate)->count();
$dayarray=[1];
}
elseif($getweekday =='Wednesday')
{
$wednesday = Carbon::parse($getdate)->count();
$dayarray=[2];
}
elseif($getweekday =='Thursday')
{
$thursday = Carbon::parse($getdate)->count();
$dayarray=[3];
}
elseif($getweekday =='Friday')
{
$firday = Carbon::parse($getdate)->count();
$dayarray=[4];
}
elseif($getweekday =='Saturday')
{
$saturday = Carbon::parse($getdate)->count();
$dayarray=[5];
}
elseif($getweekday =='Sunday')
{
$sunday = Carbon::parse($getdate)->count();
$dayarray=[6];
}
<script>
const ctx = document.getElementById('chart1').getContext('2d');
const myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'],
datasets: [{
label: 'Visitor Volume by weekday',
data: [{{ $dayarray}}],
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: {
y: {
beginAtZero: true
}
}
}
});
but when i try to run the code it gives the error of
Could not parse '[{"created_at":"2022-06-24 18:50:05"},{"created_at":"2022-06-26 13:24:42"},{"created_at":"2022-06-24 18:50:05"},{"created_at":"2022-06-26 13:24:42"},{"created_at":"2022-06-26 13:24:42"},{"created_at":"2022-06-26 13:24:42"}]': DateTime::__construct(): Failed to parse time string ([{"created_at":"2022-06-24 18:50:05"},{"created_at":"2022-06-26 13:24:42"},{"created_at":"2022-06-24 18:50:05"},{"created_at":"2022-06-26 13:24:42"},{"created_at":"2022-06-26 13:24:42"},{"created_at":"2022-06-26 13:24:42"}]) at position 0 ([): Unexpected character
I like to ask what is the error in the code , did I miss anything?
PS. I would also like to ask how to pass the data to the charts . i have a premade charts
You can use array reduce() function for this purpose. It is a php array function that you can find docs in here and also for laravel collection
$dayCounts = DB::table('watchlists')
->select('created_at')
->get()
->reduce(function ($car, $item) {
$day = Carbon::parse($item->created_at)->format('l');
$car[$day] = ($car[$day] ?? 0) + 1;
return $car;
});

Chart.js using json data

I have a jsfiddle here - https://jsfiddle.net/nhww0uor/4/
I have a simple line graph using chart.js
The data is hard coded in the code.
How do I do the same thing but with data from json
var data = {
'January' : '65',
'February' : '59',
'March' : '80',
'April' : '81',
'May' : '56',
'June' : '55'
}
const CHART = document.getElementById('lineChart');
var lineChart = new Chart(CHART, {
type: 'line',
data: {
labels: ['January','February','March','April','May','June'],
datasets:[
{
label: 'My first dataset',
fill: false,
lineTension: 0,
backgroundColor: "rgba(75,192,192,0.4)",
borderColor: "rgba(75,192,192,1)",
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
borderJointStyle: 'miter',
data: [65,59,80,81,56,55]
}
]
}
})
Considering you have the following JSON data ...
{
"January": 65,
"February": 59,
"March": 80,
"April": 81,
"May": 56,
"June": 55
}
You can use Object.keys() and Object.values() methods to parse labels and data respectively from that JSON data, for creating the chart.
Example
var data = {
"January": 65,
"February": 59,
"March": 80,
"April": 81,
"May": 56,
"June": 55
}
const CHART = document.getElementById('lineChart');
var lineChart = new Chart(CHART, {
type: 'line',
data: {
labels: Object.keys(data),
datasets: [{
label: 'My first dataset',
fill: false,
lineTension: 0,
backgroundColor: "rgba(75,192,192,0.4)",
borderColor: "rgba(75,192,192,1)",
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
borderJointStyle: 'miter',
data: Object.values(data)
}]
}
})
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.0/Chart.bundle.js"></script>
<div class="container">
<div class="row">
<div class="col-sm-6">
<canvas id="lineChart" width="400" height="400"></canvas>
</div>
<div class="col-sm-6">
</div>
</div>
</div>

Why is here a number?

I am doing a bar chart and I have a problem with names of columns. I was trying also to give names of x and yAxes but here was a problem too.
That's my dates from database:
[{ "id": "1", "paliwo": "200", "przebieg": "150", "jedzenie": "0" }]
My code:
$(document).ready(function() {
$.ajax({
url: "data.php",
method: "GET",
success: function(data) {
console.log(data);
var paliwo = [];
var przebieg = [];
for (var i in data) {
paliwo.push(data[i].paliwo);
przebieg.push(data[i].przebieg);
}
var chartdata = {
labels: paliwo,
przebieg,
datasets: [{
label: 'Paliwo',
backgroundColor: 'rgba(200, 200, 200, 0.75)',
borderColor: 'rgba(200, 200, 200, 0.75)',
hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
hoverBorderColor: 'rgba(200, 200, 200, 1)',
data: paliwo
}, {
label: 'Przebieg',
backgroundColor: 'rgba(200, 200, 200, 0.75)',
borderColor: 'rgba(200, 200, 200, 0.75)',
hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
hoverBorderColor: 'rgba(200, 200, 200, 1)',
data: przebieg
}]
};
var ctx = $("#mycanvas");
var barGraph = new Chart(ctx, {
type: 'bar',
data: chartdata,
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
},
error: function(data) {
console.log(data);
}
});
});
this is because you have given labels:paliwo; Labels denotes the x axis and paliwo contains [200]

Chart.js color is not getting changed

i am trying to use chart js to create a dashboard. i am trying to being with a the example given their getting started page. but color of the bars are always gray. i know i am missing something very trivial but i cannot figure out what. any help will be hugely appreciated
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="Scripts/jquery-1.10.2.js"></script>
<script src="Scripts/Chart.js"></script>
<script type="text/javascript">
$(document).ready(function () {
//var ctx = $("#myChart");
var ctx = document.getElementById("myChart");
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]
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
});
</script>
</head>
<body>
<canvas id="myChart" width="400" height="400"></canvas>
</body>
</html>
Just add backgroundColor to your dataset to change the color of all bars.
...
backgroundColor: 'rgba(121, 121, 255, 0.2)',
...
If you pass it an array of colors, it will set the color bar by bar for the dataset
...
backgroundColor: ['rgba(121, 121, 255, 0.2)', 'rgba(255, 121, 121, 0.2)',... ],
...
Fiddle - http://jsfiddle.net/L9qsb3h4/
Fiddle (bar by bar) - http://jsfiddle.net/0b98k2g8/