How to move Google Charts colour settings from file to another - javascript

So I am working on a project where the code already exists.
On 2 files as below, I need to remove the colour settings from the first file to the second file somehow in the IF statement.
The reason is the first file will be populated/injected with info from the backend but in order to do so I have to remove from the datasets propeties (label, fillColor, strokeColor, pointColor, pointStrokeColor, pointHighlightFill and pointHighlightStroke) array in file 1 to file 2 so to seperate styles from actual data that will be injected
I have tried simply adding the datasets section to the second file but just doesn't show anything - can it be added to the Chart.types.Line.extend object or the AJAX section somehow?
Many thanks in advance
File 1: (Will have data injected to it):
{
"labels":[
"1 Feb",
"8 Feb",
"15 Feb",
"22 Feb",
"29 Feb",
"7 Mar",
"14 Mar",
"21 Mar",
"28 Mar",
"4 Apr",
"11 Apr",
"18 Apr",
"25 Apr"
],
"datasets":[
{
"label":"Tenders",
"fillColor":"rgba(253,0,20,0.2)",
"strokeColor":"rgba(253,0,20,1)",
"pointColor":"#fff",
"pointStrokeColor":"rgba(253,0,20,1)",
"pointHighlightFill":"#fff",
"pointHighlightStroke":"rgba(253,0,20,1)",
"data":[
77,
55,
40,
65,
59,
80,
81,
56,
55,
65,
59,
80,
75
]
}
]
}
File 2: (Where I want datasets properties to be):
if (document.getElementById("chart_div_won")) {
Chart.types.Line.extend({
name: "LineAlt",
initialize: function(data) {
Chart.types.Line.prototype.initialize.apply(this, arguments);
var xLabels = this.scale.xLabels;
var xLabelsLength = xLabels.length;
xLabels.forEach(function(label, i) {
if (i % 4 != 0 || i <= 1 || i == xLabelsLength - 1)
xLabels[i] = '';
})
}
});
var form_data = {};
$.ajax({
type: "GET",
url: "../../../sample_data/chart1.json",
data: form_data,
success: function(response) {
var ctx = document.getElementById("chart_div_won").getContext("2d");
var options = {
responsive: true,
maintainAspectRatio: true,
pointDotRadius: 5,
showXLabels: 5,
};
var myLineChart = new Chart(ctx).LineAlt(response, options);
},
error: function() {
$('div#chart-container').html('<div class="notification-body"><p class="notification-heading">Loading error...</p><p class="notification-description">Unfortunatley for some reason visual data failed to load.</p></div>');
},
dataType: "json",
contentType: "application/json; charset=utf-8",
});
}

So I this is as far as I have got:
if (document.getElementById("chart_div_won")) {
Chart.types.Line.extend({
name: "LineAlt",
initialize: function(data) {
Chart.types.Line.prototype.initialize.apply(this, arguments);
var xLabels = this.scale.xLabels;
var xLabelsLength = xLabels.length;
xLabels.forEach(function(label, i) {
if (i % 4 != 0 || i <= 1 || i == xLabelsLength - 1)
xLabels[i] = '';
})
}
});
var datasets = [{
"label":"Tenders",
"fillColor":"rgba(253,0,20,0.2)",
"strokeColor":"rgba(253,0,20,1)",
"pointColor":"#fff",
"pointStrokeColor":"rgba(253,0,20,1)",
"pointHighlightFill":"#fff",
"pointHighlightStroke":"rgba(253,0,20,1)"}
];
var form_data = {};
$.ajax({
type: "GET",
url: "../../../sample_data/chart1.json",
data: form_data.push(datasets),
success: function(response) {
var ctx = document.getElementById("chart_div_won").getContext("2d");
var options = {
responsive: true,
maintainAspectRatio: true,
pointDotRadius: 5,
showXLabels: 5,
};
var myLineChart = new Chart(ctx).LineAlt(response, options);
},
error: function() {
$('div#chart-container').html('<div class="notification-body"><p class="notification-heading">Loading error...</p><p class="notification-description">Unfortunatley for some reason visual data failed to load.</p></div>');
},
data: form_data.push(datasets),
dataType: "json",
contentType: "application/json; charset=utf-8",
});
}
I am trying to add an array of datasets, then add that to the array in the first file, in the datasets array. No luck but I think my code in syntactically wrong in this answer above

For anyone with this or a similar problem. It was easy in the end. All I had to do was add each property on at the end of the array.
Code
myLineChart.datasets[0].fillColor = "rgba(253,0,20,0.2)";
And so on

Related

If the entries in the model are made on the same date then the fields of this model must be summed up

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

Write response from JSON Array to Google Chart and HTML

I have a google chart code like below
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Type');
data.addColumn('number', 'Total');
data.addRows([
['Damage', 3],
['Lost', 1]
]);
// Instantiate and draw our chart, passing in some options.
var chart = new
google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
I want to insert with json api array like below
"status": 200,
"message": "OK",
"data": [
{
"_id": {
"report_type": "robbery"
},
"report_type": "robbery",
"Counts": 11
},
{
"_id": {
"report_type": "property_damage"
},
"report_type": "property_damage",
"Counts": 39
},
{
"_id": {
"report_type": null
},
"report_type": null,
"Counts": 2
}
]
I want to change type and total in the google chart above with report_type and Counts value in api.
I have tried write code below, but the results is not coming
function drawChart() {
$.ajax({
url: "api-url",
type: "GET",
success: function (data) {
var arrReport = [['Type', 'Total']];
$.each(data, function (index, value) {
arrReport.push([value.data.report_type, value.data.Counts]);
});
var options = {
'width':400,
'height':300
};
var figures = google.visualization.arrayToDataTable(arrReport)
var chart = new
google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(figures, google.visualization.PieChart(options));
}
});
}
Do you know where's the error from my code ?
Thank you
if the following is the json you are receiving...
"status": 200,
"message": "OK",
"data": [
{
"_id": {
"report_type": "robbery"
},
"report_type": "robbery",
"Counts": 11
},
{
"_id": {
"report_type": "property_damage"
},
"report_type": "property_damage",
"Counts": 39
},
{
"_id": {
"report_type": null
},
"report_type": null,
"Counts": 2
}
]
in the following data argument,
then you should be looping on --> data.data
and accessing the values as --> value.report_type & value.Counts
var arrReport = [['Type', 'Total']];
$.each(data.data, function (index, value) {
arrReport.push([value.report_type, value.Counts]);
});
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
var options = {
width: 400,
height: 300
};
var arrReport = [['Type', 'Total']];
var figures;
// will fail here on SO
$.ajax({
url: 'api-url',
type: 'GET'
}).done(function (data) {
drawChart(data);
}).fail(function () {
// draw with hard-coded data, for example purposes
var data = {
"status": 200,
"message": "OK",
"data": [
{
"_id": {
"report_type": "robbery"
},
"report_type": "robbery",
"Counts": 11
},
{
"_id": {
"report_type": "property_damage"
},
"report_type": "property_damage",
"Counts": 39
},
{
"_id": {
"report_type": null
},
"report_type": null,
"Counts": 2
}
]
};
drawChart(data);
});
function drawChart(data) {
$.each(data.data, function (index, value) {
arrReport.push([value.report_type, value.Counts]);
});
figures = google.visualization.arrayToDataTable(arrReport);
chart.draw(figures, options);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
NOTES:
1) you should be using the newer library loader.js
<script src="https://www.gstatic.com/charts/loader.js"></script>
instead of jsapi, according to the release notes...
The version of Google Charts that remains available via the jsapi loader is no longer being updated consistently. Please use the new gstatic loader from now on.
this will only change the load statement, see above snippet.
2) google.visualization.PieChart -- should be removed here --> chart.draw(figures, options);
I think you are missing with API Url Like,
$.ajax({
url: "api-url",
type: "GET",
success: function (data) {
});
Assumed the API Url in a variable so it should be-
$.ajax({
url: api-url,
type: "GET",
success: function (data) {
});

Making a simple 2 dimensional array

I'm trying to create a real-time graph like this: http://www.flotcharts.org/flot/examples/ajax/index.html
The problem is that I need data like:
var rawData = [
[1325347200000, 60], [1328025600000, 100], [1330531200000, 15], [1333209600000, 50]
];
$(document).ready(function () {
var rx_bytes = [];
var iteration = 0;
//Options
var options = {
lines: {
show: true
},
points: {
show: true
},
xaxis: {
tickDecimals: 0,
tickSize: 1
}
};
//Initial Plot
$.plot("#networkStats", rx_bytes, options);
function getStatistics() {
iteration++;
$.ajax({
url: '/getStatistics',
type: 'post',
dataType: 'json',
success: function (statistics) {
console.log(statistics);
var network = statistics.networks.eth0;
rx_bytes.push({
index: iteration,
data: network.rx_bytes
});
console.log(rx_bytes);
//Plot
$.plot("#cpuStats", [rx_bytes], options);
//get data again
getStatistics();
}
});
}
getStatistics();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
And my array output is like this: http://prntscr.com/i3y8ve
How do I make an array like the one above?
This should solve it:
rx_bytes.push([
iteration,
network.rx_bytes
]);

c3.js - How can I set the y lines value to the first value from url (json data)

How can I set the y lines value to the first value from URL? (JSON data)
var chartDisplay = c3.generate({
bindto: '.chart',
data: {
url: '/stats',
mimeType: 'json',
},
grid: {
y: {
lines: [ {
value: data1 <---- this is what I cant figure out
}
]
}
}
});
The json data looks like this:
{
"data1": 3000,
"data2": [
3000,
3300.0,
3410.0,
4520.0,
]
}
try adding this to your chart declaration,
onrendered: function () {
this.api.ygrids([
{value: this.data.targets[0].values[0].value, text:'data 1 value'},
]);
},
this.api is basically the same as the 'chart' variable, and this.data is a pointer to the loaded dataset. targets[0] will be the first series loaded (data1) and values[0].value will be the value of the first entry
http://jsfiddle.net/y7axwubf/1/

JSONp Datetime Javascript query fails on data.sparkfun iot

been trying to select data from data.sparkfun based on when its posted. I want to display weather data from the currenttime and a day back.
The stream is at: LINK
I am no coder, just hacking my way through here.
One json line is like this:
[{
"humidity": "37.8919",
"hectopascals": "1017.7725",
"rainin": "0.0000",
"tempc": "21.3162",
"winddir": "-1",
"windspeedkmh": "0.0000",
"windgustkmh_10m": "0.0000",
"timestamp": "2017-02-25T15:11:08.581Z"
}]
The code I use is at: https://www.hanscees.com/photon/charts-data-sparkfun.html
function drawChart2() {
var public_key = 'yA0EjKV3owhKNx1NlN3w';
// JSONP request
var jsonData = $.ajax({
url: 'https://data.sparkfun.com/output/' + public_key + '.json',
//data: {page: 1}, see http://phant.io/docs/output/http/
// https://forum.sparkfun.com/viewtopic.php?f=44&t=40621
data: {
'gt': {
'timestamp': 'now - 2d'
}
},
dataType: 'jsonp',
}).done(function(results) {
var data = new google.visualization.DataTable();
data.addColumn('datetime', 'Time');
data.addColumn('number', 'TempC');
data.addColumn('number', 'Humidity');
$.each(results, function(i, row) {
data.addRow([
(new Date(row.timestamp)),
parseFloat(row.tempc),
parseFloat(row.humidity)
]);
}); // each row
// see https://google-developers.appspot.com/chart/interactive/docs/gallery/linechart#dual-y-charts
var materialOptions = {
chart: {
title: 'TempC, Humidity outside'
},
width: 550,
height: 500,
series: {
// Gives each series an axis name that matches the Y-axis below.
0: {
axis: 'TempC'
},
1: {
axis: 'Humid'
}
},
axes: {
// Adds labels to each axis; they don't have to match the axis names.
y: {
Pressure: {
label: 'TempC (Celsius)'
},
Humid: {
label: 'Humidity'
}
}
}
};
var materialChart = new google.charts.Line(ChartDivTemp);
materialChart.draw(data, materialOptions);
}); // results
} // jsondata
but the diagrams are either displaying all data in the json file (which makes it extremely slow), or when I use:
data: {page: 1},
it shows about 4 hours of data.
How can help to format the query correctly? This line:
data: {
'gt': {
'timestamp': 'now - 2d'
}
}
I did a post request thru Postman and it worked:
https://data.sparkfun.com/output/yA0EjKV3owhKNx1NlN3w.json?lt[timestamp]=now%20-2day
data: {
'lt': {
'timestamp': 'now - 2day'
}
}
So you code should work by adding 2day and changing gt to lt
This code does what I wanted:
// JSONP request
var jsonData = $.ajax({
url: 'https://data.sparkfun.com/output/' + public_key + '.json',
//data: {page: 1}, see http://phant.io/docs/output/http/
// https://forum.sparkfun.com/viewtopic.php?f=44&t=40621
data: {'gt': {'timestamp': 'now - 2day'}},
dataType: 'jsonp',
}).done(function (results) {

Categories