So I am trying to achieve how to show 5 name into the chart instead off all name:
here is my views.py:
def index(req):
labels = [
{"name": 'data'},
{"name": 'hello'},
{"name": 'wassup'},
{"name": "waddddup"},
{"name": "heyyyyy"},
{"name": "dsfdsfd"},
{"name": "qqqq"},
{"name": "23f3f"},
{"name": "23f"},
{"name": "zzzz"},
]
values = []
def label_chart(labels):
label_test = []
for i in labels:
label_test.append(i['name'])
dataJSON = dumps(label_test)
return dataJSON
data = {
'data': label_chart(labels),
}
return render(req, 'index.html', data)
and here is my template javascript index.html:
<script type="text/javascript">
var data_labels = JSON.parse(`{{ data | safe }}`);
console.log(data_labels);
var endpoint = '/api/chart/data/'
$.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() {
let y = [10, 3, 5, 9, 1];
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: data_labels,
datasets: [{
label: '# of Votes',
data: y,
backgroundColor: [
'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)'
],
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
}
}]
}
}
});
}
</script>
I already tried to slice in python which is like this:
data = {
'data': label_chart(labels)[:5],
}
but it will give me an error like this on browser:
VM245:1 Uncaught SyntaxError: Unexpected end of JSON input
You are slicing the JSON blob, not the list of labels, you can slice the labels with:
data = {
'data': label_chart(labels[:5]),
}
try returning list from you function label_chart and then slice it.
def label_chart(labels):
label_test = []
for i in labels:
label_test.append(i['name'])
return label_test
data = {
'data': label_chart(labels)[:5],
}
Related
1.the website takes a dataset from the user and does some query function(avg,count,max..etc) then display it in a chart when the user selects two column and one of them is string the chart doesn't work i don't know why this is happening when I select two column that are type Number the chart works.
2. the second problem for some reason when I try to use console.log in the script tag it doesn't show any thing on the console .
<script>
var a = [<%= a %>] //[ 45, 333, 100, 400 ]
var b = [<%= b %>] //[ 'UAE', 'USA', 'Qatar', 'KSA' ]
const originalData = a ;
const originalLabels = b ;
const ctx = document.getElementById('myChart').getContext('2d');
const myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: originalLabels,
datasets: [{
label: '# of Votes',
data: originalData,
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
}
}
}
});
function updateChart() {
const inputdata = document.getElementById('inputdata');
const inputcolor = document.getElementById('inputcolor');
const inputlable = document.getElementById('inputlabel');
myChart.data.datasets[0].data.push(inputdata.value);
myChart.data.datasets[0].backgroundColor.push(inputcolor.value);
myChart.data.datasets[0].borderColor.push(inputcolor.value);
myChart.data.labels.push(inputlabel.value);
myChart.update()
}
// function filterChart
function filterChart() {
myChart.data.datasets[0].data = originalData;
myChart.data.labels = originalLabels;
const filterdatanumber = document.getElementById('filterdatanumber').value;
// filter array.filter command
const filterData = myChart.data.datasets[0].data.filter(value => value >
filterdatanumber);
// create 2 new arrays for the labels + colors.
const filterLabels = [];
const filterColors = [];
// for loop + loop through the array get the matching value index0f()
let i = 0;
for (i; i < filterData.length; i++) {
const result = myChart.data.datasets[0].data.indexOf(filterData[i]);
const labelresult = myChart.data.labels[result];
const colorsresult = myChart.data.datasets[0].backgroundColor[result];
//push this into the new array
filterLabels.push(labelresult);
filterColors.push(colorsresult);
}
// reassign the array into the chart.
myChart.data.datasets[0].data = filterData;
myChart.data.labels = filterLabels;
myChart.data.datasets[0].backgroundColor = filterColors;
// update chart
myChart.update()
}
function resetChart() {
myChart.data.datasets[0].data = originalData;
myChart.data.labels = originalLabels;
myChart.update();
}
</script>
This is my callback function and i have getData(data); to get all JSON data ,
And created dataset = [ ]; (for get some specific properties from my all JSON data)
function call_some_api(getData){
request('https://someUrl..........',{json:true},(err,res,data) => {
if (err) {
console.log(err);
}
if (res.statusCode === 200){
var dataset = [];
data.forEach((value, key)=>{
dataset.push(value.close);
});
getData(data);
}
});
};
And use callback and pass my all JSON data in res.render it works normally.
But i want add dataset variable from my callback into res.render to page know variable dataset
app.get('/chart',function(req,res){
call_some_api(function(getAPI_data){
res.render('chart',{
dataChart: getAPI_data,
});
});
});
I just need to my /chart page (handlebars template) know my variable from callback function. (for build chart)
This my /chart (handlebars template)
<canvas id="myChart" width="400" height="400"></canvas>
<br><br>
<script>
const ctx = document.getElementById('myChart').getContext('2d');
const myChart = new Chart(ctx, {
type: 'line',
data: {
labels: ['Jan', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
datasets: [{
label: '# of Votes',
// I just want add in this line below.
data: dataset,
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: {
stacked: true
}
}
}
});
</script>
This error
You mean like a second argument, analog to getAPI_data ?
function call_some_api(getData){
request('https://someUrl..........',{json:true},(err,res,data) => {
if (err) {
console.log(err);
}
if (res.statusCode === 200){
var dataset = [];
// BTW this can be better/cleaner done with `.map` ;)
data.forEach((value, key)=>{
dataset.push(value.close);
});
getData(data, dataset);
}
});
};
And in your render/http endpoint
app.get('/chart',function(req,res){
call_some_api(function(getAPI_data, dataset){
res.render('chart',{
dataChart: getAPI_data,
dataset
});
});
});
NOTE: Code not tested, inline edited.
I am fairly new to javascript and I cannot get a bar chart to workout. The problem seems to be living in the chart3 data section. I can't figure out how to organize the two statements to get the proper data. I have literally tried everything to be able to display the two values next to each others in bars but nothing seems to be able to make it. Anybody spots what I am wrong here?
DATA:
{'supplier : "ARAGON", average_service_level_implied:-9.24, average_service_level_optimal: 0.495}
view.py
#method_decorator(login_required, name='dispatch')
class SupplierPage(LoginRequiredMixin,APIView):
def get(self, request, *args, **kwargs):
query = request.GET.get('search_ress', None)
context = {}
if query and request.method == 'GET':
Supplier = supplier.objects.filter(supplier = query)
context.update({'Supplier': Supplier})
return render(request, 'Supplier.html',context)
and chart.js graph
<script>
$(document).ready(function() {
var endpoint = 'items.html'
var forecastdata = []
var reference = []
;
$.ajax({
method: "GET",
url: endpoint,
success: function (data) {
reference = data.reference
forecastdata = data.forecastdata
setChart()
},
error: function (error_data) {
console.log(error_data)
}
}
)
function setChart() {
var ctx = document.getElementById('myChart3').getContext('2d');
var myChart3 = new Chart(ctx3, {
type: 'bar',
data: {
labels: ["actual service level", "optimal service level"],
datasets: [{
label: 'Service level analytics',
data: [
{% for dr in reference %}{{ dr.niveau_service_implicite}}, {% endfor %},
{% for dr in reference %}{{ dr.niveau_service_optimal}}, {% endfor %}
],
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: {
type: 'linear',
position: 'bottom',
xAxes: [{maxBarThickness: 10}],
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
}
})
Can try passing the 2 values of the bar with the setChart() function , like this :
function setChart(d1,d2) {
...
data [ d1 , d2 ]
And the extraction of the value can be done while calling the function :
reference = data.reference
forecastdata = data.forecastdata
d1 = ...
d2 = ...
setChart(d1,d2)
This chart shows correctly like so:
But this one does not display the bar:
It displays this line as incorrect where default2 is:
Unresolved variable default2
EDIT
I have commented down below for you to see and added a picture where this error displays:
EDIT
How do I make the chart above appear with bar like the other one?
Been doing these for days and hours and looked for answers here with no luck. Hopefully you can see where I went wrong.
Newbie to this so I appreciate all your help, folks!
EDIT
EDIT
chart.js
var endpoint = '/api/chart/data/';
var defaultData = [];
var labels = [];
var defaultData2 = [];
var labels2 = [];
$.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)
}
});
$.ajax({
method: "GET",
url: endpoint,
success: function (data) {
labels2 = data.labels2;
defaultData2 = data.default2; # default2 displays error/as incorrect???
setChart2()
},
error: function (error_data) {
console.log("error");
console.log(error_data)
}
});
function setChart2(){
var ctx = document.getElementById("myChart5");
var myChart5 = new Chart(ctx, {
type: 'bar',
data: {
labels2: labels2,
datasets: [{
label: 'Total',
data: defaultData2,
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,
callback: function(value) {if (value % 1 === 0) {return value;}}
}
}]
}
}
});}
function setChart(){
var ctx = document.getElementById("myChart1");
var myChart1 = new Chart(ctx, {
type: 'bar',
data: {
labels: labels,
datasets: [{
label: 'Total',
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,
callback: function(value) {if (value % 1 === 0) {return value;}}
}
}]
}
}
});
views.py
from django.shortcuts import render
from django.views.generic import View
from django.http import JsonResponse
from django.contrib.auth import get_user_model
from SiO.member.models import Member
from SiO.CoAdmin.models import Administrator
from rest_framework.views import APIView
from rest_framework.response import Response
import datetime
User = get_user_model()
class ChartView(View):
def get(self, request, *args, **kwargs):
return render(request, 'chart/ChartView.html', {})
class ChartViewMonth(View):
def get(self, request, *args, **kwargs):
return render(request, 'chart/ChartView/month.html', {})
class ChartData(APIView):
def get(self, request, format=None):
today = datetime.date.today()
qs_count = Administrator.objects.filter(association=self.request.user.association).count()
qs_count1 = Member.objects.filter(association=self.request.user.association).count()
qs_count2 = Member.objects.filter(reg_date__year=today.year,
reg_date__month=today.month).filter(
association=self.request.user.association).count()
labels2 = ["January"]
default_items2 = [qs_count2, ]
labels = ["Board", "Members"]
default_items = [qs_count, qs_count1]
data = {
"labels": labels,
"default": default_items,
"labels2": labels2,
"default2": default_items2,
}
return Response(data)
urls.py
from django.conf.urls import url
from . import views
from django.contrib.auth import get_user_model
User = get_user_model()
urlpatterns = [
url(r'^ChartView/$', views.ChartView.as_view(), name='ChartView'),
url(r'^ChartView/month$', views.ChartViewMonth.as_view(), name='ChartView/month'),
url(r'^api/chart/data/$', views.ChartData.as_view()),
]
in this code, I was able to get the data from database in the JSON format. now iam struggling to draw a chart in JS with columns as values and rows as time stamp. i have a controller(chartController) that goes into the database and extract the desired data and change it into JSON format, that is values and timestamp. then i created a route for this controller, Route::get('json/{notification_id}','ChartController#speedHistory')->name('speedhistory')
i hava a js class as follows,
document.addEventListener('DOMContentLoaded', function() {
$.getJSON("json", function getdata(data) {
console.log(data);
var pageSpeedValues = o_response;
createChartHistory(pageSpeedLabels);
});
function fetchValues(Labels, Values) {
var pageSpeedLabels = Values;
var pageSpeedValues = Labels;
createChartHistory(pageSpeedLabels);
}
// This function allows us to create a chart for the history page
function createChartHistory(pageSpeedLabels, pageSpeedValues) {
var ctx = document.getElementById("pageSpeedHistoryChart");
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: pageSpeedLabels,
datasets: [{
label: 'PageSpeed History',
data: pageSpeedValues,
backgroundColor: [
'rgba(255, 99, 132, 0.5)',
'rgba(54, 162, 235, 0.5)',
'rgba(255, 206, 86, 0.5)',
'rgba(75, 192, 192, 0.5)',
'rgba(153, 102, 255, 0.5)',
'rgba(255, 159, 64, 0.5)',
'rgba(255, 99, 132, 0.5)',
'rgba(54, 162, 235, 0.5)',
'rgba(32, 206, 86, 0.5)',
'rgba(77, 192, 192, 0.5)',
'rgba(153, 102, 255, 0.5)',
'rgba(255, 159, 64, 0.5)'
]
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true,
max: 100,
min: 0
}
}]
}
}
});
}
if(document.querySelector('#pageSpeedHistoryChart')) {
getdata();
}
});
I am not getting the data from the controller into the app.js class, any one how get the idea? iam learning js but seems a bit difficult at this point.
here is my chart controller
<?php
namespace App\Http\Controllers;
use App\Notification;
use App\Status;
use Illuminate\Http\Request;
class ChartController extends Controller
{
public function speedHistory($notification_id){
$o_notification = Notification::find(intval($notification_id));
$o_status = Status::where('name','speed')->first();
$o_response = $o_notification->statuses()->where('status_id', $o_status->id)
->select('values AS value', 'created_at AS timestamp')->orderBy('created_at','DESC')->get()
->transform(function ($item, $key) {
return collect([
'values' => $item->pivot->values,
'created_at' => $item->pivot->created_at->toDateTimeString()
]);
});
return response()->json($o_response);
}
}