implementing horizontal bar chart - javascript

I am a noob in angular. I already have a bar-chart component and I am using that component in several places across the project. now I want to implement the horizontal bar chart by modifying that bar chart component but I am stuck at this point and not moving forward. there are no errors and below code implementing a normal bar chart. Thanks in advance
bar-chart component
dataCtx: any;
bar_chart: any;
#ViewChild('barChart') barChartRef: ElementRef;
#Input() data = [];
#Input() type: string;
#Input() hoverData: Array<string>;
#Input() yLabel: any;
#Input() xLabel: any;
#Input() label?: string;
#Input() barLabel?: string;
#Input() nameObj?: any;
#Input() showLabel: boolean;
#Input() charType: string;
color = [];
#Output() onSegClick = new EventEmitter<any>();
colors: Array<string> = ["rgba(98, 228, 98, 1)", "rgba(248, 227, 117, 1)", "rgba(250, 99,131, 1)", 'red', 'blue', 'violet', 'orange'];
constructor() { }
ngOnInit() {
}
ngAfterViewInit() {
this.renderChart();
}
ngOnChanges() {
if (this.barChartRef)
this.renderChart();
}
renderChart() {
let self = this;
this.dataCtx = this.barChartRef.nativeElement.getContext('2d');
let gradient_1 = this.dataCtx.createLinearGradient(0, 0, 0, 250);
gradient_1.addColorStop(0, ' #c4743e');
gradient_1.addColorStop(1, 'transparent');
let gradient_2 = this.dataCtx.createLinearGradient(0, 0, 0, 250);
gradient_2.addColorStop(0, 'beige');
gradient_2.addColorStop(1, 'transparent');
let gradient_3 = this.dataCtx.createLinearGradient(0, 0, 0, 250);
gradient_3.addColorStop(0, '#2f7ca7');
gradient_3.addColorStop(1, "transparent");
this.bar_chart = new Chart(this.dataCtx, {
type: this.charType || 'bar',
data: {
labels: this.nameObj.map(obj => obj.name),
datasets: this.setChartData()
},
options: {
legend: {
display: this.showLabel,
labels: {
padding: 20,
fontStyle: 'bold',
fontSize: 16,
}
},
title: {
display: this.label ? true : false,
text: this.label,
fontStyle: 'bold',
fontSize: 20,
},
showAllTooltips: true,
toolTips: {
mode: 'index',
intersect: true
},
scales: {
xAxes: [{
categoryPercentage: 0.65,
// barPercentage: 1.0,
// barThickness: 50,
maxBarThickness: 50,
display: true,
scaleLabel: {
display: true,
fontStyle: 'bold',
labelString: this.yLabel
},
ticks: {
autoSkip: false
},
gridLines: {
color: 'rgba(88, 88, 88, 0.35)',
lineWidth: 2.5
}
}],
yAxes: [{
// stacked: true,
display: true,
scaleLabel: {
display: true,
fontStyle: 'bold',
labelString: this.xLabel
},
ticks: {
min: 0,
max: 100,
},
gridLines: {
color: 'rgba(0, 78, 162, 0.5)',
lineWidth: 0.5
}
}]
},
responsive: true,
onClick: function (evt, arr) {
if (arr[0]) {
self.onSegClick.emit(arr[0]._index);
}
},
}
});
}
cohortProf(options) {
let cohortData = [{
data: this.data.map(coh => Math.floor(coh.proficiency * 100)),
backgroundColor: '#0080FF',
options
}]
return cohortData;
}
testData() {
let testData = [];
this.data.forEach((d, i) => {
let val = Math.floor(d.data * 100);
testData.push(val);
this.color.push('#' + (Math.random() * 0xFFFFFF << 0).toString(16));
// this.color.push('hsl('+ val +', 100%, 50%)')
});
return testData;
}
testProf(options) {
let testData = [{
data: this.testData(),
backgroundColor: this.color,
options
}]
return testData;
}
subjectProf(options) {
let subData = [];
let strat = this.hoverData;
this.data.filter((d, index) => { subData.push({ "data": d, "backgroundColor": this.colors[index], options, label: strat[index] }) });
return subData;
}
setChartData() {
let dataSet: any;
let fixed_options = {
borderColor: 'tranparent',
borderWidth: 2,
pointBorderColor: 'transparent',
pointBackgroundColor: 'transparent',
pointHoverBackgroundColor: "#fff",
pointHighlightFill: "#fff",
pointRadius: 3,
pointHitRadius: 20,
pointBorderWidth: 1,
};
switch (this.type) {
case 'test': {
dataSet = this.testProf(fixed_options);
break;
}
case 'cohort': {
dataSet = this.cohortProf(fixed_options);
break;
}
case 'grouped-chart': {
dataSet = this.subjectProf(fixed_options);
break;
}
case 'single-bar': {
dataSet = [{
data: this.data,
backgroundColor: this.colors,
label: 'Analytics'
}];
break;
}
default: {
break;
}
}
return dataSet;
}
}
reusing the same component to implement horizontal bar chart
horizantalChart = {
data:[[10,20],[30,40]]
}
<bar-chart [type]="'single-bar'" [hoverData]="['Experts Avg. Score', 'Others Avg. Score']" barLabel="Proficiency"
[data]="horizontalChart.data" [nameObj]="uploadAnalytics.analytics" yLabel="Quizzes" chartType="horizontalBar"
[xLabel]="'Average Upload Score'" [showLabel]="true" (onSegClick)="selectBar($event)"></bar-chart>
The output of the code looks like this

Inside the renderChart method of your bar-chart component, the chart is currently created as follows:
this.bar_chart = new Chart(this.dataCtx, {
type: 'bar',
...
This will always create a vertical bar chart. It should be rewritten as follows in order to consider the type provided by the #Input() decorator.
this.bar_chart = new Chart(this.dataCtx, {
type: this.type,
...
Probably this.bar_chart is then no longer an appropriate name and should be amended to avoid future misunderstandings.

Related

How to draw multiple color bars in a bar chart along a Horizontal Line using chart.js

I am making a chart using chart.js in react environment.
If you look at the second image, what if there is 130% along the Horizontal Line? 100 is formed with gray and above 100 green. I also want to make it in the same format as above.
I've been looking for it for 2 days, but I don't know how to do it
This is my work in progress.
I want to make it in this format.
This is my code.
import { Bar, Chart } from 'react-chartjs-2';
import annotationPlugin from "chartjs-plugin-annotation";
import "chartjs-plugin-datalabels";
import ChartDataLabels from "chartjs-plugin-datalabels";
Chart.register([annotationPlugin], [ChartDataLabels] );
let chartColors = {
yellow: '#F4D068',
green: '#4CC26F',
gray: '#EBEBEB'
};
const data = {
labels: ['January', 'February', 'March', 'April', 'May', 'June'],
datasets: [
{
label: 'My First dataset',
backgroundColor: [],
borderColor: '#EBEBEB',
borderWidth: 1,
borderRadius: 10,
data: [65, 140, 130, 200, 56, 35, 80],
random: ['Check', 'Out', 'Udemy', 'Course', 'Charjs 3', 'Coming Out', 'Next week'],
},
],
};
let colorChangeValue = 100;
let dataset = data.datasets[0];
for (let i = 0; i < dataset.data.length; i++) {
if (dataset.data[i] > colorChangeValue) {
dataset.backgroundColor[i] = chartColors.green;
if (dataset.data[i] < 100) {
dataset.backgroundColor[i] = chartColors.gray;
}
}
if (dataset.data[i] < colorChangeValue) {
dataset.backgroundColor[i] = chartColors.yellow;
}
}
return (
<Bar
data={data}
width={100}
height={70}
options={{
scales: {
x: {
stacked: true,
grid: {
display: false,
},
},
y: {
stacked: true,
grid: {
},
ticks: {
maxTicksLimit: 1
}
}
},
plugins: {
legend: {
display: false
},
title: {
display: true,
text: "범례1",
padding: {
bottom: 30
},
weight: "bold",
color: "#00325c",
font: {
size: 13
},
align: "start"
},
datalabels: {
display: true,
color: "black",
anchor: 'end',
align: 'top',
formatter: function (value) {
return "\n" + value + "%";
}
}
},
annotations: {
myHorizontalLine: {
type: "line",
scaleID: "y",
borderWidth: 3,
borderColor: "#333333",
value: 100,
borderDash: [8, 8],
label: {
font: {
weight: "normal"
},
rotation: "auto",
enabled: true
}
},
}
}}
/>
)
You could define a second dataset that does nothing but drawing the gray space up to the limit of 100.
{
backgroundColor: '#DDD',
hoverBackgroundColor: '#DDD',
data: [100, 0, 0, 0, 100, 100],
datalabels: {
display: false
}
},
Also make sure that only the x-axis has the option stacked: true.
Together with this, you'll also need to adjust some other options. A tooltip.filter for example will prevent Chart.js from showing a tooltip for the second dataset.
tooltip: {
filter: tooltipItem => !tooltipItem.datasetIndex
},
Please take a look at the StackBlitz with your amended code and see how it works.

Using ChartJs in Vue3 /not vue-chartjs/

I know vue-chartjs is not supported in Vue3. So I decided to do it using ChartJs itself.
I have a form containing radio button and calendar and passing it to the chart component.
I couldn't write it in methods and I wrote it in created.
Because of this when I change the form inputs my chart is not reacting. I tried watching the values of prop coming from my form and it's reactive.
Help me
Here's my TestGraph.vue component
<template>
<div class="param-container">
<h3>Params</h3>
<p> {{radioCalendarUrl.frequency}}, {{radioCalendarUrl.from}}, {{radioCalendarUrl.to}} </p>
<button #click="testMethod">Click</button>
</div>
<canvas id="test_chart" style="margin-left: auto; margin-right: auto; width: 80%; height: 600px;"/>
</template>
<script>
import { ref, computed, defineComponent, onMounted} from "vue";
export default {
name: 'Posts',
data() {
return{
}
},
computed: {
propsToUrl() {
return '/?frequency='+`${this.radioCalendarUrl.frequency}`+'&from='+`${this.radioCalendarUrl.from}`+'&to='+`${this.radioCalendarUrl.to}`
}
},
methods: {
testMethod() {
console.log(`${this.radioCalendarUrl.frequency}`)
console.log(`${this.radioCalendarUrl.from}`)
console.log(`${this.radioCalendarUrl.to}`)
console.log(this.propsToUrl)
},
},
watch: {
radioCalendarUrl: function(newVal, oldVal) { // watch it
console.log('Prop changed: ', newVal, ' | was: ', oldVal)
}
},
props: {
radioCalendarUrl: {
type: Object,
required: true
}
},
async created() {
const getData = (result) => {
return [result.map(function(e) {
return e.date;
}),
result.map(function(e) {
return e.desktop;
}),
result.map(function(e) {
return e.tablet;
}),
result.map(function(e) {
return e.mobile;
}),
result.map(function(e) {
return e.total;
})]
}
let url1 = "http://localhost:8085/all-page-view" + this.propsToUrl
const res1 = await fetch(url1)
const result_pv = await res1.json()
const res2 = await fetch("http://localhost:8085/uniq-user" + this.propsToUrl)
const result_uu = await res2.json()
console.log(url1)
console.log("DATA")
console.log(result_pv)
const [xlabels, pc_pv_data, tablet_pv_data, smartphone_pv_data, total_pv_data] = [...getData(result_pv)]
console.log([xlabels, pc_pv_data, tablet_pv_data, smartphone_pv_data, total_pv_data])
const [xlabels_useless, pc_uu_data, tablet_uu_data, smartphone_uu_data, total_uu_data] = [...getData(result_uu)]
// eslint-disable-next-line
//function createChart(){
var ctx = document.getElementById('test_chart');
//グラフ詳細
// eslint-disable-next-line
new Chart(ctx, {
type: 'bar',
data: {
datasets: [
//ページビュー
//PCページビュー
{
type: 'bar',
label: 'PCページビュー',
data: pc_pv_data,
order: 5,
backgroundColor: 'rgb(116,181,236)',
borderColor: 'rgb(116,181,236)',
barPercentage: 0.4
},
//タブレットページビュー
{
type: 'bar',
label: 'タブレットページビュー',
data: tablet_pv_data,
order: 6,
backgroundColor: 'rgb(244,192,121)',
borderColor: 'rgb(244,192,121)',
barPercentage: 0.4
},
// スマホページビュー
{
type: 'bar',
label: 'スマホページビュー',
data: smartphone_pv_data,
order: 7,
backgroundColor: 'rgb(255,191,227)',
borderColor: 'rgb(255,191,227)',
barPercentage: 0.4
},
//ページビュー合計
{
type: 'bar',
label: 'ページビュー合計',
data: total_pv_data,
order: 8,
backgroundColor: 'rgb(205,243,179)',
borderColor: 'rgb(205,243,179)',
barPercentage: 0.4
},
//UU
//PCUU
{
type: 'line',
label: 'PCUU',
data: pc_uu_data,
fill: false,
order: 1,
backgroundColor: 'rgb(59,128,186)',
borderColor: 'rgb(59,128,186)',
pointBorderWidth: 1,
pointHoverRadius: 10,
lineTension: 0,
pointStyle: 'rectRot'
},
//タブレットUU
{
type: 'line',
label: 'タブレットUU',
data: tablet_uu_data,
fill: false,
order: 2,
backgroundColor: 'rgb(247,129,42)',
borderColor: 'rgb(247,129,42)',
pointBorderWidth: 1,
pointHoverRadius: 10,
lineTension: 0,
pointStyle: 'triangle'
},
//スマホUU
{
type: 'line',
label: 'スマホUU',
data: smartphone_uu_data,
order: 3,
backgroundColor: 'rgb(183,111,151)',
borderColor: 'rgb(183,111,151)',
fill: false,
pointBorderWidth: 1,
pointHoverRadius: 10,
lineTension: 0,
pointStyle: 'rect'
},
//UU合計
{
type: 'line',
label: 'UU合計',
data: total_uu_data,
fill: false,
order: 4,
backgroundColor: 'rgb(142,177,110)',
borderColor: 'rgb(142,177,110)',
pointBorderWidth: 1,
pointHoverRadius: 10,
lineTension: 0,
pointStyle: 'circle'
}
],
labels: xlabels
},
options: {
responsive: false,
legend: {
position: 'bottom',
labels: {
fontColor: '#333',
usePointStyle: true,
fontSize: 12,
boxWidth: 40,
},
},
scales: {
yAxes: [{
scaleLabel: {
display: false,
labelString: 'ページビューとUU回数'
},
stacked: true,
ticks: {
suggestedMin: 100,
callback: function(value) {
return value + '回';
}
}
}],
xAxes: [{
stacked: true
}],
}
}
});
//}
},
mounted() {
},
}
</script>

ChartJS passing data dynamically, then passing data into variables

I am trying to figure out how to take the 3 hardcoded variables [index, fieldName, aggType] and pass data in to them from a json file dynamically, and then pass that variable into the (inData) function that I created, and then finally pass those into the charts that I have created. I am not exactly sure how to go about referencing the data and getting it into the variable. I placed my code below. Please, let me know if I can clarify this any, it is a bit confusing. Index name is the ES index, fieldname is the field to aggregate against and aggType is the type of aggregation like count, sum etc...There was a suggested answer to this question, using the forEach option, however, this was not a good fit for my situation, as it would be necessary to pass multiple lines in some queries, or singular lines in others. The forEach option would force us to deal with each option in an individual way. We wanted to be able to pass the query as a whole. Thank you for all your help. The anser I came up with is below.
mainchart.js
$('#chartType').change(function(index, val) {
buildChart($(this).val())
})
function line() {
let labels = []
let data = []
let index = 'issflightplan';
let fieldName = 'VehicleType';
let aggtype = 'count';
$.getJSON("http://localhost:3000/data/issflightplan/VehicleType/count/", function (inData) {
aggregationName = index + "|" + fieldName + "|" + aggtype
for (keyNo in inData.aggregations[aggregationName].buckets) {
labels.push(inData.aggregations[aggregationName].buckets[keyNo].key)
data.push(inData.aggregations[aggregationName].buckets[keyNo].doc_count)
}
// });
console.log(data)
var ctx = document.getElementById('myChart').getContext('2d');
var gradient = ctx.createLinearGradient(450, 0, 0, 0);
gradient.addColorStop(0, 'rgb(0,99,132)');
gradient.addColorStop(1, 'rgb(255,99,132)')
var gradient2 = ctx.createLinearGradient(0, 0, 0, 450);
gradient2.addColorStop(0, 'rgb(0,50,600)');
gradient2.addColorStop(1, 'rgb(150,0,100)')
function drillDownChart(click, mydata) {
if (mydata[0]) {
var x = mydata[0]['_index'];
window.location.href = 'https://chart-js.com/'
}
};
var chart = new Chart(ctx, {
type: 'line',
data: {
labels: labels,
datasets: [{
label: 'My New Line Chart',
data: data,
backgroundColor: gradient,
borderColor: 'blue',
borderWidth: 1,
borderDash: [10, 5, 10, 2],
borderDashOffset: 10,
borderCapStyle: 'round',
borderJoinStyle: 'bevel',
cubicInterpolationMode: '',
fill: true,
lineTension: 0.2,
pointBackgroundColor: ['red', 'yellow', 'purple', 'orange', 'green', 'blue', 'pink'],
pointBorderColor: ['red', 'yellow', 'purple', 'orange', 'green', 'blue', 'pink'],
pointBorderWidth: 3,
pointRadius: 2,
pointStyle: 'circle',
pointHitRadius: 20,
pointHoverBackgroundColor: 'purple',
pointHoverBorderColor: 'pink',
pointHoverBorderWidth: 5,
pointHoverRadius: 10,
showLine: true,
spanGaps: true,
steppedLine: false
}, {
label: ['My New Line Chart 2'],
data: data.datapoints2,
// backgroundColor: gradient2,
borderColor: gradient2,
fill: false
}]
},
// Configuration options go here
options: {
onClick: drillDownChart,
// onClick: updateChart,
legendCallback: function (line) {
var text = [];
text.push('<ul class="legendClass">');
for (var i = 0; i < chart.data.datasets.length; i++) {
text.push('<li class = style = "background: ' + chart.data.datasets[i].backgroundColor + ' ">');
text.push(chart.data.datasets.label[i]);
text.push('</li>')
}
text.push('</ul>');
return text.join("");
},
ticks: {
autoSkip: true
},
responsive: true,
maintainAspectRatio: false,
legend: {
display: true,
fontSize: 16,
responsive: true,
},
plugins: {
title: {
display: true,
// text: obj.title,
position: "top",
fontSize: 16,
fontFamily: "New Times Roman",
fontColor: 'blue',
fontStyle: 'bold',
padding: 10,
lineHeight: 1.2,
},
legend: {
display: true,
//need to be able to pass the options into you from the data
position: "bottom",
align: 'center',
fullWidth: true,
// onClick: alertBox,
// onHover: changeFontColor,
labels: {
boxWidth: 20,
fontSize: 10,
fontStyle: 'bold',
fontColor: 'black',
fontFamily: 'Times New Roman',
padding: 10,
usePointStyle: 'circle',
},
annotation: {
annotations: [{
type: 'line',
mode: 'vertical',
value: '18B',
borderColor: 'red',
borderWidth: 2
}],
tooltips: {
enabled: true,
mode: 'index',
intersect: false,
position: 'nearest',
backgroundColor: 'rgb(0, 0, 132)',
titleFontFamily: 'New Times Roman',
titleFontSize: 16,
titleFontStyle: 'normal',
titleFontColor: '#yellow',
titleSpacing: 10,
titleMarginbottom: 15,
bodyFontFamily: 'New Times roman',
bodyFontSize: 15,
bodyFontStyle: 'normal',
bodyFontColor: 'rgb(0,15,132)',
bodySpacing: 3,
xPadding: 10,
yPadding: 10,
caretPadding: 5,
cornerRadius: 20,
// multiKeyBackground: '()',
displayColors: true,
callbacks: {
title: function (tooltipItems, data) {
// Pick first xLabel for now
var title = chartType;
var labels = data.labels;
var labelCount = labels ? labels.length : 0;
if (tooltipItems.length > 0) {
var item = tooltipItems[0];
if (item.xLabel) {
title = labels[item.index];
} else if (labelCount > 0 && item.index < labelCount) {
title = labels[item.index];
}
}
return title;
},
events: ["mousemove", "mouseout", "click", "touchstart", "touchmove", "touchend"],
onClick: function (event, arry) {
getcurrentfilter(event, arry)
}
}
}
}
}
}
}
});
console.log(data)
})
}
mydata.json
{
"hits": [...],
"aggregations": {
"issflightplan|VehicleType|count":{
"meta": {...},
"buckets": [
{
"key": "Progress",
"doc_count":77
},
"issflightplan|CrewSize|count": {
"meta": {...},
"buckets": [
{
"key": "",
"doc_count": 32
},
I wanted to post the answer that I came up, and it is working well, and gives the ability to add some different options to the function later on.
function line() {
let labels = []
let data = []
$.getJSON("http://localhost:3000/data/issflightplan/VehicleType/count/", function (inData) {
let aggregationName = []
for (aggName in inData.aggregations) {
console.log(aggName)
for( bucket in inData.aggregations[aggName].buckets) {
labels.push(inData.aggregations[aggName].buckets[bucket].key)
data.push(inData.aggregations[aggName].buckets[bucket].doc_count)
}
}

issue in creating stacked horizontal bar-chart in chartJs

I need to create a stacked horizontal bar chart and for the below code the chart is coming as horizontal but it is not stacked. I have created a seperate component for chart and using it in another component I gone through few stacked overflow articles but didn't help. I not able to find out the issue. any help is very appreciated.
horizontal-chart.component.ts
export class HorizontalBarchartComponent implements OnInit {
dataCtx: any;
bar_chart: any;
#ViewChild('horizontalbarChart') horizontalbarChartRef: ElementRef;
#Input() data = [];
#Input() yLabel: any;
#Input() xLabel: any;
#Input() nameObj?: any;
#Input() stacked:boolean;
#Input() hoverData:Array<any>;
colors: Array<string> = ["rgba(98, 228, 98, 1)", "rgba(248, 227, 117, 1)", "rgba(250, 99,131, 1)"]
constructor() { }
ngAfterViewInit() {
this.renderChart();
}
ngOnChanges() {
if (this.horizontalbarChartRef){
this.renderChart();
}
}
renderChart() {
this.dataCtx = this.horizontalbarChartRef.nativeElement.getContext('2d');
this.bar_chart = new Chart(this.dataCtx, {
type: 'horizontalBar',
data: {
labels: this.nameObj.map(obj => obj.name),
datasets:this.setData()
},
options: {
legend: {
display: true,
position: 'bottom',
labels: {
padding: 20,
fontStyle: 'bold',
fontSize: 12,
}
},
scales: {
xAxes: [{
stacked: true,
position:'top',
display: true,
scaleLabel: {
display: true,
fontStyle: 'bold',
labelString: this.yLabel
},
ticks: {
autoSkip: false,
beginAtZero: true,
max:10
},
gridLines: {
display:false,
}
}],
yAxes: [{
stacked: true,
categoryPercentage: 1,
maxBarThickness: 50,
display: true,
scaleLabel: {
display: true,
fontStyle: 'bold',
labelString: this.xLabel
},
ticks: {
min: 0,
},
gridLines: {
display:false
}
}]
},
responsive: true,
}
});
}
setData(){
let fixed_options ={
borderColor: 'transparent',
borderWidth: 2,
pointBorderColor: 'transparent',
pointBackgroundColor: 'transparent',
pointHoverBackgroundColor: "#fff",
pointHighlightFill: "#fff",
pointRadius: 3,
pointHitRadius: 20,
pointBorderWidth: 1,
}
if(this.stacked){
let subData = [];
this.data.filter((d,index) => { subData.push({"data":d, "backgroundColor": this.colors[index],"label": this.hoverData[index], fixed_options }) });
return subData;
}
else{
return [{"data": this.data,"backgroundColor":'rgba(98, 228, 98, 1)',"label":`Upload/Sketch's Per Factor Scores`}]
}
}
}
another.component.html
<horizontal-barchart class="col-md-10" [data]="horizontalBar.data" yLabel="Percentage"
[xLabel]="'student names'" [nameObj]="quizOrTestAnalysis" [stacked]="true"
[hoverData]="['Proficient Answers', 'Elimination Answers', 'Random Answers']">
</horizontal-barchart>
another.component.ts
horizontalBar = {
data:[[10],[20],[30]],
}
The output of the provided code
I had set ticks:{max:10} on x:axis which restricting the chart from showing further data

ChartJS makes unwanted horizontal line on Safari

I'm currently working with ChartJS.
It works fine on Firefox and Chrome.
On Safari there is horizontal lines which appear. (here there is one good on orange and two others unwanted )
I have a lot of datapoint (2 lines of 1600 data point). I don't know if it could be a cause.
My code is here.
In some other part, I update time uni and time min.
_displayChart: function(label1, label2){
var timeFormat = 'DD/MM/YYYY HH:mm';
var ctx = document.getElementById(this.heading).getContext('2d');
const data = {
// Labels should be Date objects
//labels:this._stats[1],
datasets: [{
fill: false,
label: label1,
data: this._stats[2],
borderColor: '#fe8b36',
pointRadius: 0,
backgroundColor: [
'#fe8b36'
]
},{
label: label2,
fill: false,
data: this._stats[3],
borderWidth: 1,
pointRadius: 0,
borderColor: 'rgba(99, 100, 200, 1)',
backgroundColor: [
'rgba(99, 100, 200, 0.2)'
]
}]
}
const options = {
type: 'line',
data: data,
options: {
responsive: false,
fill: false,
responsive: true,
maintainAspectRatio:!this._isMobile(),
max: this.max,
hover: {
// Overrides the global setting
mode: 'index'
},
annotation: {
drawTime: 'beforeDatasetsDraw',
events: ['click'],
annotations: []
},
legend: {
labels: {
filter: function(legendItem, chartData) {
if(legendItem.datasetIndex == 2 || legendItem.datasetIndex == 3 ){
return false;
}
return true;
}
}
},
tooltips: {
mode:'index',
intersect : false,
callbacks: {
title: function(tooltipItems, data) {
return tooltipItems[0].xLabel.format(timeFormat);
},
label: function(tooltipItems, data) {
return tooltipItems.yLabel+'%';
}
}
},
scales: {
xAxes: [{
type: 'time',
display: true,
time:{
unit:'day',
min:moment(Date.now()-this.monthTs),
max:this._stats[1][this._stats[1].length]
}
}],
yAxes: [{
ticks: {
beginAtZero: true,
},
display: true
}]
}
}
}
this._chart = new Chart(ctx, options);
},
When I'm applying this, I have no problem:
this._chart.options.scales.xAxes[0].time.unit = 'month';
this._chart.options.scales.xAxes[0].time.stepSize = 1;
this._chart.options.scales.xAxes[0].time.min = this._stats[1][0];
this._chart.options.scales.xAxes[0].time.max = this._stats[1][this._stats[1].length-1];
Thanks

Categories