vuechartJs make a label dynamic - javascript

I'm trying to do a pie chart with vue chart, I am trying to convert an object into an array to update de label in vuechartjs and make it dynamic according to the api, but it seems almost impossible. My goal is to fetch the concert name in the label and then fetch (data) how many booking we have for each concert. Would someone would be kind enough to help ? I have tried everything. thanks Here is my code :
<script>
import { Pie } from 'vue-chartjs'
export default {
extends: Pie,
data () {
return {
bandNames:[],
booking:[],
bandName:[],
data:[],
chartData: {
labels:[],
datasets: [{
borderWidth: 1,
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)'
],
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)',
],
data: [1000]
}]
},
options: {
legend: {
display: true
},
responsive: true,
maintainAspectRatio: false
}
}
},
created(){
var vm = this;
this.axios
.get('http://localhost:3000/booking', {})
.then(function (response) {
console.log(response.data);
vm.booking = response.data;
});
this.axios
.get('http://localhost:3000/concerts', {})
.then(function (response) {
console.log(response.data);
vm.bandNames = response.data;
vm.bandNames.forEach((item)=>{
vm.bandName.push(item.band)
})
vm.chartData.labels = vm.bandName[0]
var data = []
var i = vm.bandName.length
for(var a = 0 ; a < i ; a++){
data.push([vm.bandName[a]])
vm.chartData.labels = data
}
});
},
mounted () {
this.renderChart(this.chartData, this.options)
}
}

You can directly push the labels to the chartOptions in the loop , so change this :
vm.bandNames.forEach((item)=>{
vm.bandName.push(item.band)
})
vm.chartData.labels = vm.bandName[0]
by :
vm.bandNames.forEach((item)=>{
vm.chartData.labels.push(item.band)
})

Related

Chart is not visible when exporting date from excel sheet (chart.js)

I'm trying to export the excel data and want to show chart according to that data but chart is not visible. When I use mock data chart is working fine but not when I'm exporting the data. Issue is with the date. data = [['2023-02-01', '2023-02-03'],
['2023-02-03', '2023-02-06'],
['2023-02-06', '2023-02-09']]
when I'm using above date as mock, it is working fine but when I use same format date through excel its not working.
export class BarGraphComponent {
public chart: any;
workBook: any = null;
labels: any = [];
data: any = [];
constructor() {}
ngOnInit() {
}
onFileChange(ev: any) {
let jsonData = null;
const reader = new FileReader();
const file = ev.target.files[0];
reader.onload = (event) => {
const data = reader.result;
this.workBook = XLSX.read(data, { type: 'binary'});
jsonData = this.workBook.SheetNames.reduce((initial: any, name: any) => {
const sheet = this.workBook.Sheets[name];
initial[name] = XLSX.utils.sheet_to_json(sheet, {raw: false});
return initial;
}, {});
for(let i = 0; i<jsonData.Sheet1.length; i++){
this.data.push([jsonData.Sheet1[i].Start, jsonData.Sheet1[i].Finish]);
this.labels.push(jsonData.Sheet1[i].Activity)
}
}
reader.readAsBinaryString(file);
this.createChart();
}
createChart(){
console.log(this.data);
this.chart = new Chart("MyChart", {
type: 'bar', //this denotes tha type of chart
data: {// values on X-Axis
labels: this.labels,
datasets: [{
label: 'PS-6 Data in Graph Format',
data: this.data,
backgroundColor: [
'rgba(255, 26, 104, 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, 26, 104, 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(0, 0, 0, 1)',
],
borderWidth: 1
}]
},
options: {
indexAxis:'y',
scales: {
x: {
min: '2023-02-01',
type: 'time',
time: {,
unit: 'day',
}
}
}
}
});
}
}

Can I add some variables to my chart.js in page know that variables?

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.

Targeting and manipulating a chart bars and labels in a Vue.js component

I am New to Vue and chart js, what I am trying to do is to target the chart, Add, delete and update the chart's labels and data values.
I have a link to chartJs documentation, but where I am stuck at is in what scope in the export default {} block could I target the data.
i have my chart set in a Vue component, I am also using a CLI Webpack setup.
// HERE IS MY HTML
<v-flex xs12 md12 width="400px" height="400px" mt-5 >
<canvas id="myChart" ></canvas>
</v-flex>
export default {
methods: {
CreateChart(chartId, chartData) {
const ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['JavaScript', 'NodeJs', 'VueJs', 'DataBase'],
datasets: [{
label: '# of votes',
data: [12, 15, 23, 15],
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)',
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
}
},
mounted() {
let data = data;
this.CreateChart('chart', data);
},
}
Now, as per ChartJs official documentation, I could have a function, I think after the createChart() method within the `methods{}' scope, the function should allow me target the bars or labels for instance in the following way
function addData(myChart, label, data) {
chart.data.labels.push(label);
chart.data.datasets.forEach((dataset) => {
dataset.data.push(data);
});
chart.update();
}
function removeData(chart) {
chart.data.labels.pop();
chart.data.datasets.forEach((dataset) => {
dataset.data.pop();
});
chart.update();
}
Thanks in advance

One chart cant display the data

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()),
]

how to draw chart from json data in js

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);
}
}

Categories