Related
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;
});
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 have a server.js page and it get datas from database. I want to use this datas in a HTML page. How can I get this datas.
I don't use Express but Hapi (because i'm happy lol).
This is my code :
<script>var ctx = document.getElementById('graph').getContext('2d');
var graph = new Chart(ctx, {
type: 'line',
data: {
labels: ['Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi', 'Dimanche'],
datasets: [{
label: 'CPU',
data: [22, 19, 25, 65, 30, 47, 14],
backgroundColor: "rgba(153,255,51,0.4)"
}, {
label: 'RAM',
data: [31, 29, 31, 35, 28, 34, 30],
backgroundColor: "rgba(255,153,0,0.4)"
}]
}
});
</script>
I want to change "22, 19, 25, 65, 30, 47, 14" by the new values gets with postgreSQL.
Thanks for your help.