I would like to display two lines in a Chart.js line chart. The required data from the database I have a JSON file with 2 objects.
Now I want to display them in the line chart. If I only want to display one data set it is no problem. When displaying two lines at the same time I have no idea what to do. I tried to call the objects and then output them, but the output is always undefined.
What am I doing wrong here?
Error:
Cannot read property 'current_week' of undefined
JSON Output:
{"current":[{"current_week":23},{"current_week":636},{"current_week":237}],"last":[{"last_week":235},{"last_week":74},{"last_week":737},{"last_week":767},{"last_week":546},{"last_week":73},{"last_week":453}]}
JS Chart.js Code:
$(document).ready(function() {
$.ajax({
url : "http://localhost/r6team-new/admin/includes/stats/website-weekly-stats.php",
type : "GET",
success : function(data) {
console.log(data);
var current_week = [];
var last_week = [];
for(var i in data) {
current_week.push(data.current[i].current_week);
last_week.push(data.last[i].last_week);
}
console.log(current_week);
console.log(last_week);
var visitorsChart = {
labels: ['MO', 'DI', 'MI', 'DO', 'FR', 'SA', 'SO'],
datasets: [{
type : 'line',
data : current_week,
backgroundColor : 'transparent',
borderColor : '#007bff',
pointBorderColor : '#007bff',
pointBackgroundColor: '#007bff',
fill : false
},
{
type : 'line',
data : last_week,
backgroundColor : 'tansparent',
borderColor : '#ced4da',
pointBorderColor : '#ced4da',
pointBackgroundColor: '#ced4da',
fill : false
}]
};
var ctx = $("#visitors-chart");
var LineGraph = new Chart(ctx, {
data: visitorsChart,
});
},
});
});
your loop is incorrect
var current_week = [];
var last_week = [];
for(var i in data["current_week"]) {
current_week.push(i["current_week"]);
}
for(var i in data["last_week"]) {
last_week.push(i["last_week"]);
}
or make it more easier
$(document).ready(function() {
$.ajax({
url : "http://localhost/r6team-new/admin/includes/stats/website-weekly-stats.php",
type : "GET",
success : function(data) {
var visitorsChart = {
labels: ['MO', 'DI', 'MI', 'DO', 'FR', 'SA', 'SO'],
datasets: [{
...
//current_week
data: data["current"].map(d => d["current_week"])
},
{
...
//last_week
data: data["last"].map(d => d["last_week"])
}]
};
var ctx = $("#visitors-chart");
var LineGraph = new Chart(ctx, {
data: visitorsChart
});
},
});
});
Related
I have a model
class paidparking(models.Model):
adress = models.ForeignKey(Parking, on_delete=models.SET_NULL, null=True, verbose_name='Адрес парковки')
carnumber = models.CharField(max_length=150,verbose_name='Номер автомобиля')
amountoftime = models.IntegerField(verbose_name='Количество времени')
price = models.FloatField(verbose_name='Цена')
telephone = models.CharField(max_length=20,verbose_name='Номер телефона')
email = models.EmailField(verbose_name='Электронный адрес',null=True,blank=True )
datetimepaidparking = models.DateTimeField(auto_now_add=True, verbose_name='Дата и время оплаты')
expirationdate = models.DateField(null=True,verbose_name='Дата начала срока действия')
expirationtime = models.TimeField(null=True,verbose_name='Время начала срока действия')
enddateandtime = models.DateTimeField(null=True,blank=True,verbose_name='Окончание срока действия')
There is a function
startdate = datetime.strptime(request.POST['startdate'], '%d.%m.%Y')
enddate = datetime.strptime(request.POST['enddate'], '%d.%m.%Y')
paymentparking = paidparking.objects.filter(expirationdate__range=(startdate, enddate)).values('expirationdate',
'price')
In JS, I get this data and draw graphs
$.ajax({
type: "POST",
url: "date",
data: {
'startdate': finalDateStrStart, 'enddate': finalDateStrEnd,
},
dataType: "json",
cache: false,
success: function (data) {
if (data.result) {
var expirationdates = [];
var prices = [];
for (let i = 0; i < data.result.length; i++) {
expirationdates.push(data.result[i].expirationdate);
prices.push(data.result[i].price);
}
if(window.chart instanceof Chart)
{
window.chart.destroy();
}
var ctx = document.getElementById("line").getContext("2d");
var chart = new Chart(ctx, {
type: 'line',
data: {
labels: expirationdates,
datasets: [{
label: 'Оплата парковочных пространств',
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(144,204,244)',
data: prices,
}]
},
options: {
}
});
var ctx = document.getElementById("bar").getContext("2d");
var chart = new Chart(ctx, {
type: 'bar',
data: {
labels: expirationdates,
datasets: [{
label: 'Оплата парковочных пространств',
backgroundColor: 'rgb(144,204,244)',
borderColor: 'rgb(255, 99, 132)',
data: prices,
}]
},
options: {
}
});
}
}
});
return JsonResponse({'result': list(paymentparking)})
As a result, I get:
I need to make a query that would sum the values from the price field for the same date in the expirationdate field
Right now my query outputs all records if the expirationdate field falls within the date range between startdate and enddate
You have to use the trick with values and annotate as described very well here:
from django.db.models import Sum
qs = paidparking.objects.values('expirationdate').annotate(Sum('price'))
# if you want to order by date:
qs = qs.order_by('expirationdate')
This will output a queryset a list of dictionnaries containing expirationdate and price__sum as keys.
Edit:
For your question in the comment, just add the filter at the beginning of the query:
paidparking.objects.filter(expirationdate__range=(startdate, enddate)).values('expirationdate').annotate(Sum('price'))
You need to use annotate in django orm to get the output for the same.
from django.db.models import Sum
PaidParking.objects.values('expirationdate', 'price') \
.annotate(parking_price=Sum('price')) \
.order_by('-expirationdate')
I suppose this answer is suffice for the asked query.
Reference: For Basic understanding of the query how it works follow this link
I need to display attributes of each object exisiting in data.How can I access the objects in my template?
Views.py
data = []
for e in rep:
data.append({
'time' : e.time,
'power' : e.power
})
return JsonResponse({'data':data},status=200)
template
success : function(response){
console.log(response)
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: [***here i need to access my objects***],
datasets: [{
label: "Consumption",
data: [{% for e in data %}'{{ e.power }}',{% endfor %}]}})
}
Kind regards.
I have been struggling with this one for days now, really need some help. I need to apply gradient colors and some custom styling to our ChartJs bar chart, that contains call reporting data which comes from the back-end server. I found a way how to apply the styles and gradients, but can't figure out how to configure datasets to display correct data from the server, instead of some random numbers (eg. 10,20,30), like I tried for gradientGreen below. Any ideas?
//main html
<div class="row mb-4 mt-4">
<div class="col-9">
<h4 class="text-center">Call Distribution</h4>
#await Component.InvokeAsync("HourlyCallTotals", new { from = Model.From, to = Model.To, customer = Model.customer, site = Model.site })
</div>
//component html
#model CallReporter.ViewModels.BasicFilter
<div id="hourlyChart">
</div>
<script>
var HourlyCallData = #Html.RenderAction("HourlyTotals", "Calls", "", new { from = Model.from.ToString("s"), to = Model.to.ToString("s"), customer = Model.customer, site = Model.site })
</script>
//relevant part of JS function for Chart
function hoursChartAjax() {
var hourlyChart = $('#hourlyChart').html('<canvas width="400" height="300"></canvas>').find('canvas')[0].getContext('2d');
// set gradients for bars
let gradientGreen = hourlyChart.createLinearGradient(0, 0, 0, 400);
gradientGreen.addColorStop(0, '#66d8b0');
gradientGreen.addColorStop(1, '#1299ce');
let gradientBlue = hourlyChart.createLinearGradient(0, 0, 0, 400);
gradientBlue.addColorStop(0, '#1299ce');
gradientBlue.addColorStop(1, '#2544b7');
if (hourlyChart !== undefined) {
$.get(base + "Calls/HourlyTotals", { from: from.format(), to: to.format(), customer: currentCustomer.id, site: currentSite }, function (data) {
// set the default fonts for the chart
Chart.defaults.global.defaultFontFamily = 'Nunito';
Chart.defaults.global.defaultFontColor = '#787878';
Chart.defaults.global.defaultFontSize = 12;
var chart = new Chart(hourlyChart, {
type: 'bar',
data: {
labels: ['6AM', '9AM', '12AM', '3PM', '6PM', '9PM', '12PM'],
datasets: [
{
label: 'Total outgoing calls',
backgroundColor: gradientBlue,
data: HourlyCallData
},
{
label: 'Total incoming calls',
backgroundColor: gradientGreen,
data: [10, 20, 30]
}
]
},
//relevant part of back-end code that returns call data as Json
totalsContainer.Totals = allCallsHourly.OrderBy(x => x.Date).ToList();
return Json(new
{
labels = totalsContainer.Totals.Select(x => x.Date.ToString("hh tt")),
datasets = new List<object>() {
new { label = "Total Outgoing Calls", backgroundColor = "#1299CE", data = totalsContainer.Totals.Select(x => x.TotalOutgoingCalls) },
new { label = "Total Incoming Calls", backgroundColor = "#00B050", data = totalsContainer.Totals.Select(x => x.TotalIncomingCalls) } }
});
Attached img with console log and error, after trying solution below:
If the data comes formatted in the right way, you can just write this:
var chart = new Chart(hourlyChart, {
type: 'bar',
data: data: data
}
If not you could do it like so:
var chart = new Chart(hourlyChart, {
type: 'bar',
data: {
labels: data.labels,
datasets: [
{
label: data.datasets[0].label,
backgroundColor: gradientBlue,
data: data.datasets[0].data
},
{
label: data.datasets[1].label,
backgroundColor: gradientGreen,
data: data.datasets[1].data
}
]
}
}
I'd like to plot some charts using Chart.js.
I have a script that gets two arrays from a database in JSON format.
The two arrays are:
-An array of Temperature (float)
-An array of Time (Obtained by the Database at the moment in which a temperature enters it by means of the function Current_Timestamp ())
I'd like to be able to graph the temperatures depending on the date with Chart.js
$(document).ready(function(){
$.ajax({
url : "http://localhost/js/data.php",
type: "GET",
success : function(data) {
console.log(data);
var datos = {
VectorTemp : [],
VectorFecha : []
}
var len = data.length;
for (var i = 0; i<len;i++){
if (data[i].chipID == 1){
datos.VectorTemp.push(data[i].temp);
datos.VectorFecha.push(data[i].fecha);
}
}
console.log(datos);
var ctx = $("#line-chartcanvas");
var data = {
labels: [],
datasets: [
{
x: datos.VectorFecha[1],
y: datos.VectorTemp[1]
}
]
};
var options = {
responsive: true,
title: {
display: true,
text: "Chart.js Time Scale"
},
}
var chart = new Chart (ctx, {
type: "line",
data : data,
options: options
});
},
error: function(data) {
console.log(data);
},
});
});
I have a rails app that fetches currency information data of the value of the sterling pound compared to the Kenyan shilling from a JSON API.
I want to use this data to plot a time-series graph of the value of the pound over a long period of time.
I'm using AJAX to populate data to a highcharts chart and my code is as follows:
<div id="currency", style="width: 220px, height:320px">
<script type="text/javascript">
$(document).ready(function(){
localhost = {}; //global namespace variable
localhost.currenctHTML = ""; //currency HTML built here
localhost.currencyValue = []; //array of percentage changes
localhost.currencyDate = []; //array of currency names
localhost.chart1 = {yAxisMin : null, yAxisMax : null};//obj holds things belonging to chart1
var url = '/forexes.json'
$.ajax({
url: url,
cache: false,
dataType: 'jsonp', //will set cache to false by default
context: localhost,
complete: function(data){
var a=JSON.parse(data.responseText);
// console.log(a);
var data_mapped = a.map(function (data){
return data.forex;
}).map(function (data) {
return {
currencyDate: data.published_at,
currencyValue: data.mean
}
});
this.currencyDate = _.pluck(data_mapped, 'currencyDate');
this.currencyValue = _.pluck(data_mapped, 'currencyValue');
console.log(this.currencyDate);
this.chart1.data.series[0].data = this.currencyValue;
this.chart1.data.xAxis.categories = this.currencyDate;
chart = new Highcharts.Chart(this.chart1.data);
}
});
localhost.chart1.data = { //js single-threaded, this obj created before callback function completed
chart: {
renderTo: "currency"
},
title: {
text: "Forex by Day"
},
xAxis: {
categories: null, //will be assigned array value during ajax callback
title: {
text: null
}
},
yAxis: {
title: {
text: "Pounds"
}
},
tooltip: {
formatter: function() {
return Highcharts.dateFormat("%B %e, %Y", this.x) + ': ' +
"$" + Highcharts.numberFormat(this.y, 2);
}
},
series: [{
name: 'Pound',
data: null
}
]
};
});
</script>
</div>
**** returns
this.chart1.data.xAxis.categories = ["2003-01-01T00:00:00.000Z", "2003-01-02T00:00:00.000Z", "2003-01-03T00:00:00.000Z", "2003-01-04T00:00:00.000Z", "2003-01-05T00:00:00.000Z"]
this.chart1.data.series[0].data = [147.653, 148.007, 147.971, 148.202, 148.384, 147.888]
How do I use this data to generate a highstocks line chart resembling this
In the highstock you cannot use categories, only datetime type, so you should parse your data to timestamp and use it in the data.