Vue.js using chart.js options not working - vue.js

Hey guys I am currently using example code for vue-chartjs but when I'm trying to add options it does not allow me to add it for some reason. Maybe I am misplacing it, but I'm not sure.
Here is my source code.
// CommitChart.js
import { Bar } from 'vue-chartjs'
function getNum(){return Math.floor(Math.random() * 100);}
export default {
extends: Bar,
mounted () {
// Overwriting base render method with actual data.
this.renderChart({
labels: ['Yeah', 'What', 'Turnup'],
datasets: [
{
label: 'Skimp me',
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
],
data: [getNum(), getNum(), getNum()],
borderWidth: 1
}
],
// ATTEMPTING TO ADD OPTIONS.
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
})
}
}
Everything works but I cannot figure out why this is wrong. Thanks!

You can overwrite the default chart options. Just pass the options object as a second parameter to the render method.
Right now your options are within the first object passed in.

Related

errors during render vue-chart js

I am trying render Pie chart via vue-chartjs library.
But I have several mistakes, and I can't understand, how to solve it..
<template>
<div>
<div class="page-title">
<h3>История записей</h3>
</div>
<div class="history-chart">
<canvas ref="canvas"></canvas>
</div>
<Loader v-if="loading" />
<p class="center" v-else-if="!records.length">Записей пока нет. <router-link to="/record"> Добавьте первую
</router-link>
</p>
<section v-else>
<HistoryTable :records="items" />
<Paginate v-model="page" :page-count="pageCount" :click-handler="pageChangeHandler" :prev-text="'Назад'"
:next-text="'Вперед'" :container-class="'pagination'" :page-class="'waves-effect'" />
</section>
</div>
</template>
<script>
import paginationMixin from '#/mixins/pagination.mixin';
import HistoryTable from '#/components/HistoryTable.vue';
import Loader from '#/components/app/Loader.vue';
import { Pie } from 'vue-chartjs'
export default {
name: 'history',
extends: Pie,
mixins: [paginationMixin],
data: () => ({
loading: true,
records: [],
}),
components: {
HistoryTable,
Loader
},
async mounted() {
this.records = await this.$store.dispatch("fetchRecords");
const categories = await this.$store.dispatch("fetchCategories");
this.setup(categories)
this.loading = false
},
methods: {
setup(categories) {
this.setupPagination(this.records.map(record => {
return {
...record,
categoryName: categories.find(c => c.id === record.categoryId).title,
typeClass: record.type === 'income' ? 'green' : 'red',
typeText: record.type === 'income' ? 'Доход' : 'Расход',
}
}))
this.renderChart({
labels: categories.map(c => c.title),
datasets: [{
label: 'Расходы по категориям',
data: categories.map(c => {
return this.records.reduce((total, r) => {
if (r.categoryId === c.id && r.type === 'outcome') {
total += +r.amount
}
return total
}, 0)
}),
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
}]
})
},
},
}
</script>
These errors appears when start project..
What kind of 'chartData' console want?
Why this.renderChart is not a function? I wrote that this is a function in methods.
What kind of 'in' operator I uses?
I solved the problem.
If downgrade version from v4 -> v3 for vuechartjs and chart js from v3 -> v2 all be all right.

How to put vertical dashed gridlines on Highcharts heatmap

I'm plotting a HighCharts heatmap of a wafer with around 50~70k points (it's like a CPU/processor silicon wafer). I need to put horizontal and vertical gridlines visible on the map, so that our engineers can easily figure out what's going on with the actual unit.
I have two concerns:
Horizontal gridlines are already OK, but the vertical gridlines are not drawn or visible. I thought, I just need to set gridZIndex=4. Kindly see image below - it should be drawn based on xAxis.tickPositions values (similar to yAxis)
I put some color options I found, but none of them could change the grid's color.
So far this is my code:
var option = {
chart: {
type: 'heatmap',
zoomType: 'xy',
},
boost: {
useGPUTranslations: true
},
title: {
text: chrt_title,
align: 'left',
x: 0,
style: {
fontSize: '12px',
}
},
exporting: {
buttons: {
contextButton: {
menuItems: [
'viewFullscreen', 'downloadPNG', 'downloadXLS'
]
}
},
enable: true,
},
xAxis: {
title: {
text: null
},
labels: {
enabled: false,
},
tickPositions: [1, 19, 43, 67, 91, 115, 139, 163, 183],
gridZIndex: 4, // DOESN'T WORK
gridLineDashStyle: 'Dash',
gridLineWidth: 1, // DOESN'T WORK
lineColor: 'red',
minorTickColor: 'red',
tickColor: 'red'
},
yAxis: {
title: {
text: null
},
reversed: true,
labels: {
enabled: false,
},
tickPositions: [1, 82, 116, 174, 272, 370, 428, 462, 544]
gridZIndex: 4, // ONLY PUT THIS AND WORKS ALREADY
gridLineDashStyle: 'Dash', // THIS WORKS TOO (Dot,Solid,etc)
lineColor: 'red',
minorTickColor: 'red',
tickColor: 'red'
},
colorAxis: {
stops: colrstops,
min: minval,
max: maxval,
startOnTick: true,
endOnTick: true,
labels: {
format: '{value}',
style: {
fontSize: '8px',
fontFamily: 'Verdana, sans-serif'
}
}
},
series: [{
boostThreshold: 100,
borderWidth: 0,
nullColor: '#ffffff',
tooltip: {
headerFormat: chrt_title + '<br/>',
pointFormat: 'RB{point.y} SL{point.x} <b>{point.value}</b>'
},
turboThreshold: Number.MAX_VALUE, // #3404, remove after 4.0.5 release
data: data
}]
}
As you can see, both xAxis and yAxis have gridZIndex = 4, gridLineDashStyle = 'Dash', but only the yAxis that gives the horizontal gridlines, no luck for xAxis (assuming this is where need to set the vertical gridlines) :(
the only similar question i found reg vertical gridlines is this one:
Highcharts: xAxis with vertical gridlines
but I tried to put the gridLineWidth=1, still nothin's happening T-T please help. thanks very much.
Update:
I temporarily replaced my option{} based on #ppotaczek sample but vertical gridlines still did not appeared.
Then I played with my own option{}, tried to add min and max in xAxis, and tried to temporarily removed my dynamic data and use #ppotaczek sample, the layout remains the same (no vertical gridlines)..
Also thought it has something to do with the version i'm using..? it's 9.0.1 - so I tried to update to latest 9.1.1, but also have same result.
var option = {
chart: {
type: 'heatmap',
},
xAxis: {
tickPositions: [1, 19, 43, 67, 91, 115, 139, 163, 183],
min: 1,
max: 183,
gridZIndex: 4, // DOESN'T WORK
gridLineDashStyle: 'Dash',
gridLineWidth: 1, // DOESN'T WORK
lineColor: 'red',
minorTickColor: 'red',
tickColor: 'red'
},
yAxis: {
title: {
text: null
},
reversed: true,
labels: {
enabled: false,
},
tickPositions: [1, 82, 116, 174, 272, 370, 428, 462, 544],
gridLineDashStyle: 'Dash', // THIS WORKS TOO (Dot,Solid,etc)
lineColor: 'red',
minorTickColor: 'red',
tickColor: 'red',
},
colorAxis: {},
series: [{
data: [
[10, 0, 1],
[20, 1, 5],
[30, 1, 5],
],
}]
}

The chart list is not showing

This is my chart code
datasets: [
{
label: "Fraction KG",
data: data,
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(200, 121, 121, 0.2)",
],
},
],
labels: label
And this is how my chart looks:
Why is not the list beside the chart not showing is there some option value yu have to set?
this is the pie component
PieChart.js
import { Pie, mixins } from 'vue-chartjs';
import globalOptionsMixin from "./globalOptionsMixin";
export default {
name: 'pie-chart',
extends: Pie,
mixins: [mixins.reactiveProp, globalOptionsMixin],
props: {
extraOptions: {
type: Object,
default: () => ({})
}
},
data() {
return {
ctx: null
};
},
mounted() {
this.$watch(
'chartData',
(newVal, oldVal) => {
if (!oldVal) {
debugger;
this.renderChart(this.chartData, this.extraOptions);
}
},
{ immediate: true }
);
}
};
The ChartJs labels are determined by the labels property. In your example, this is set to an unknown variable called label. This should be an array of strings.
For example:
labels: ['Italy', 'India', 'Japan', 'USA']
You could set this array to your label variable, wherever it is defined:
const label = ['Italy', 'India', 'Japan', 'USA'];
{
...
labels: label
}
Template contain chart tag
<chartjs-pie :labels="labels" :data="dataset" :bind="true"></chartjs-pie>
Then pass data through script
data: function data() {
return {
labels: ['Italy', 'India', 'Japan', 'USA'],
dataset: [..]
};
},

Trying to get _index of clicked bar in ChartJS

I have a bar chart in vue-charts where when clicked I want to display the background data in a table. This is the render
startPie: function(canvas, type){
let chart = new Chart(canvas, {
type: type,
data: {
labels: this.labels,
datasets: this.chart_data
},
options: {
responsive: true,
animation:{ animateScale:true },
title: { display: false },
legend: { display: false },
scales: {
yAxes: [{
gridLines: {
color: "#989898"
},
ticks: {
fontColor: "#989898",
fontSize: 16,
beginAtZero: true,
callback: function(value) {
let ranges = [
{ divider: 1e6, suffix: 'M' },
{ divider: 1e3, suffix: 'k' }
];
function formatNumber(n) {
for (let i = 0; i < ranges.length; i++) {
if (n >= ranges[i].divider) {
return (n / ranges[i].divider).toString() + ranges[i].suffix;
}
}
return n;
}
return '$' + formatNumber(value);
}
}
}],
xAxes: [{
ticks: {
fontColor: "#989898",
fontSize: 12
}
}]
},
plugins: {
datalabels: {
anchor: 'center',
font: {
size: 16,
weight: 'bold'
},
formatter: function(value, context) {
return '$' + Number(value).toLocaleString();
},
color: 'white'
}
},
'onClick':(evt, item) => {
console.log('CLICK', item[0]);
}
}
})
}
In the onClick Event in the console I can see the index
CLICK ChartElement {_chart: Chart, _datasetIndex: 0, _index: 4,
hidden: false, _xScale: ChartElement, …}
I can't access it though without an error. I have tried
item[0]._index, item[0]['_index'], item[0]['ChartElement']._index, item[0]['ChartElement']['_index']
Any help is appreciated.
Unfortunately, the onClick event handler is poorly documented. You could try to define the data in a separate variable outside of the chart configuration.
const data = [55, 68, 82, 48, 75, 45, 67];
Then, you can define the onClick event handler as follows:
options: {
...
onClick: (event, item) => {
const idx = chart.getElementAtEvent(event)[0]._index;
console.log(data[idx]);
}
}
const labels = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul"];
const data = [55, 68, 82, 48, 75, 45, 67];
let chart = new Chart(document.getElementById('myChart'), {
type: 'bar',
data: {
labels: labels,
datasets: [{
label: "My First Dataset",
data: data,
backgroundColor: ["rgba(255, 99, 132, 0.2)", "rgba(255, 159, 64, 0.2)", "rgba(255, 205, 86, 0.2)", "rgba(75, 192, 192, 0.2)", "rgba(54, 162, 235, 0.2)", "rgba(153, 102, 255, 0.2)", "rgba(201, 203, 207, 0.2)"],
borderColor: ["rgb(255, 99, 132)", "rgb(255, 159, 64)", "rgb(255, 205, 86)", "rgb(75, 192, 192)", "rgb(54, 162, 235)", "rgb(153, 102, 255)", "rgb(201, 203, 207)"],
borderWidth: 1
}]
},
options: {
responsive: true,
title: {
display: false
},
legend: {
display: false
},
scales: {
yAxes: [{
gridLines: {
color: "#989898"
},
ticks: {
fontColor: "#989898",
fontSize: 16,
beginAtZero: true
}
}]
},
plugins: {
datalabels: {
anchor: 'center',
font: {
size: 16,
weight: 'bold'
},
formatter: function(value, context) {
return '$' + Number(value).toLocaleString();
},
color: 'white'
}
},
onClick: (evt, item) => {
const idx = chart.getElementAtEvent(event)[0]._index;
console.log(data[idx]);
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.js"></script>
<canvas id="myChart" height="80"></canvas>

How can I for loop data in chart js with vue js

I want to for loop the labels and data so I'll never use this again labels: [this.transaction_per_day[0].Day... and data: [this.transaction_per_day[0].Amount.... I just realized when the user transacts on the next day, the data will not show in the bar graph. The problem is when I change the index into i inside the bracket instead of 0,1,2,3. It only displays the first index which is the 0. Can somebody help regarding my problem? Here's my code
retrieveTransactionPerDay : function() {
var self = this
axios.post(this.urlRoot + this.api + "retrieve_transaction_per_day.php")
.then(response => {
console.log(response);
vm.transaction_per_day = response.data
for(var i = 0; i < this.transaction_per_day.length; i++) {
var ctxChart = self.$refs.myChart.getContext('2d')
var myChart = new Chart(ctxChart, {
type: 'bar',
data: {
labels: [this.transaction_per_day[0].Day, this.transaction_per_day[1].Day, this.transaction_per_day[2].Day, this.transaction_per_day[3].Day],
datasets: [{
label: 'Transaction per day',
data: [this.transaction_per_day[0].Amount, this.transaction_per_day[1].Amount, this.transaction_per_day[2].Amount, this.transaction_per_day[3].Amount],
backgroundColor: [
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(255, 99, 132, 1)'
],
borderColor: [
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(255, 99, 132, 1)'
],
borderWidth: 1
}]
},
options: {
title : {
display : true,
text : "TRANSACTION GRAPH",
fontFamily: "sans-serif",
fontSize: 18
},
}
});
}
}).catch(e => {
console.log(e)
});
},
You can remove the for loop and use Array.map to get the label and data
vm.transaction_per_day = response.data
var myChart = new Chart(ctxChart, {
type: 'bar',
data: {
labels: vm.transaction_per_day.map(item => item.Day),
datasets: [{
label: 'Transaction per day',
data: vm.transaction_per_day.map(item => item.Amount),
backgroundColor: [
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(255, 99, 132, 1)'
],
borderColor: [
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(255, 99, 132, 1)'
],
borderWidth: 1
}]
},
options: {
title: {
display: true,
text: "TRANSACTION GRAPH",
fontFamily: "sans-serif",
fontSize: 18
},
}
});