Chart JS tooltip appears differently when set from script instead of html - javascript

I am trying to customize a Chart JS element from a template (Front Dashboard)
In the template the example is set up from the HTML as follows
<canvas class="js-chart"
data-hs-chartjs-options='{
"type": "line",
"data": {
"labels": ["1 May","2 May","3 May","4 May","5 May","6 May","7 May","8 May","9 May","10 May","11 May","12 May","13 May","14 May","15 May","16 May","17 May","18 May","19 May","20 May","21 May","22 May","23 May","24 May","25 May","26 May","27 May","28 May","29 May","30 May","31 May"],
"datasets": [{
"data": [25,18,30,31,35,35,60,60,60,75,21,20,24,20,18,17,15,17,30,120,120,120,100,90,75,90,90,90,75,70,60],
"backgroundColor": ["rgba(55, 125, 255, 0)", "rgba(255, 255, 255, 0)"],
"borderColor": "#377dff",
"borderWidth": 2,
"pointRadius": 0,
"pointHoverRadius": 0
}]
},
"options": {
"scales": {
"yAxes": [{
"display": false
}],
"xAxes": [{
"display": false
}]
},
"hover": {
"mode": "nearest",
"intersect": false
},
"tooltips": {
"postfix": "%",
"hasIndicator": true,
"intersect": false
}
}
}'>
</canvas>
This displays a nicely formatted Tooltip
but when I setup the chart from script with the same structure/config, the tooltip formatting changes and it also is clipped inside the bounds of the chart.
var myData = [];
var myLabels = [];
var myOccupancy;
function showChart() {
myData = myOccupancy.DataList;
myLabels = myOccupancy.LabelList;
console.log(myData);
console.log(myLabels);
let popCanvasName = document.getElementById("occChart");
let barChartName = new Chart(popCanvasName, {
type: 'line',
data: {
labels: myLabels,
datasets: [
{
data: myData,
backgroundColor: ['rgba(55, 125, 255, 0)', 'rgba(255, 255, 255, 0)'],
borderColor: '#377dff',
borderWidth: 2,
pointRadius: 0,
pointHoverRadius: 0
}
]
},
options: {
scales: {
yAxes: [
{
display: false
}
],
xAxes: [
{
display: false
}
]
},
hover: {
mode: 'nearest',
intersect: false
},
tooltips: {
postfix: '%',
hasIndicator: false,
intersect: false
},
legend: {
display: false
}
}
});
}
function getChartData() {
return fetch('./Index?handler=OccupancyChartData', {
method: 'get',
headers: {
'Content-Type': 'application/json;charset=UTF-8'
}
})
.then(function(response) {
console.log(response);
if (response.ok) {
return response.text();
} else {
throw Error('Response Not OK');
}
})
.then(function(text) {
try {
return JSON.parse(text);
} catch (err) {
throw Error('Method Not Found');
}
})
.then(function(responseJSON) {
myOccupancy = responseJSON;
showChart();
});
};
$(document).on('ready', function() {
getChartData();
// initialization of circles
$('.js-circle').each(function() {
var circle = $.HSCore.components.HSCircles.init($(this));
});
$('.js-chart').each(function () {
var chart = $.HSCore.components.HSChartJS.init($(this));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.9.4"></script>
<!-- as you are using v2.x of chart.js -->
<canvas id="occChart" width="640" height="480"></canvas>

The reason the formatting is different is because chart.js does not support the options postfix and hasIndicator, seems like your wrapper is styling the tooltip and taking those extra options and transforms the tooltip itself. If you want to make your chart via script you need to follow the normal documentation.
About the tooltip getting cut off guess its somewhere else that it might go wrong because standard behaviour it adjusts the tooltip placement so that it is in the chart area:
const options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [
{
label: '# of Votes',
data: [12, 19, 2, 5, 2, 3],
borderWidth: 1
},
{
label: '# of Points',
data: [7, 11, 5, 8, 3, 7],
borderWidth: 1
}
]
},
options: {
}
};
const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
canvas {
background-color : #eee;
}
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.9.4"></script>
<canvas id="chartJSContainer" width="600" height="400"></canvas>

Your code in your question is for ..... chart.js v2.xx
v3.xx is not backwards compatible with v2.xx
v3.xx has better performance, hence you might consider migrating
Anyhow, I offer you 2 solutions for both versions:
code for chart.js v2.9.4 (latest for v2.x)
code for chart.js v3.5.1 (latest for v3.x)
I migrated your code to v3.x
I used some sample data (as I cannot fetch your data from here).
v2.x
Replacing postfix: '%' with following callback function:
options: {
...
tooltips: {
usePointStyle: true,
// postfix: '%',
callbacks: { // <-- to replace 'postfix:'
label: function(context) {
return context.yLabel + '%' || '';
}
}
...
}
See following complete code for v2.x and Run code snippet to see result:
const popCanvasName = document.getElementById('occChart').getContext('2d');
let myData = [];
let myLabels = [];
const myOccupancy = { // <-- let's use sample data meanwhile
"LabelList" : ["2021-08-02","2021-08-03","2021-08-04","2021-08-05","2021-08-06"],
"DataList" : [39,41,42,30,21]
};
function showChart() {
myData = myOccupancy.DataList;
myLabels = myOccupancy.LabelList;
// console.log(myData);
// console.log(myLabels);
const barChartName = new Chart(popCanvasName, {
type: 'line',
data: {
labels: myLabels,
datasets: [{
data: myData,
backgroundColor: ['rgba(55, 125, 255, 0.5)', 'rgba(255, 255, 255, 0.5)'],
fill: true, // <-- to show backgroundColor
borderColor: '#377dff',
borderWidth: 2,
pointRadius: 0,
pointHoverRadius: 0
}]
},
options: {
aspectRatio: 5,
responsive: true,
interaction: {
intersect: false,
mode: 'nearest'
},
scales: {
yAxes: [{
display: false
}],
xAxes: [{
type: 'time', // load moment.js and adapter for this to work
display: true,
time: {
unit: 'week',
displayFormats: {
hour: 'h:mm a',
day: 'ddd',
week: 'dddd',
month: 'MMM'
},
tooltipFormat: 'dddd, MMM DD, YYYY' // modify format string to your needs
}
}]
},
tooltips: {
usePointStyle: true,
// postfix: '%',
callbacks: { // you can use this callback
label: function(context) {
return context.yLabel + '%' || '';
}
},
// hasIndicator: true,
intersect: false
},
legend: {
display: false
}
}
});
};
function getChartData() {
return fetch('./Index?handler=OccupancyChartData', {
method: 'get',
headers: {
'Content-Type': 'application/json;charset=UTF-8'
}
})
.then(function(response) {
console.log(response);
if (response.ok) {
return response.text();
} else {
throw Error('Response Not OK');
}
})
.then(function(text) {
try {
return JSON.parse(text);
} catch (err) {
throw Error('Method Not Found');
}
})
.then(function(responseJSON) {
myOccupancy = responseJSON;
showChart();
});
};
showChart();
/* We use sample data meanwhile
$(document).on('ready', function() {
// getChartData(); <-- we use sample data meanwhile
// initialization of circles
$('.js-circle').each(function() {
var circle = $.HSCore.components.HSCircles.init($(this));
});
$('.js-chart').each(function () {
var chart = $.HSCore.components.HSChartJS.init($(this));
});
});
*/
<!-- get latest version of Chart.js v2.x -->
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.9.4"></script>
<!-- You need moment.js and adapter for time to work at x-Axis -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-moment"></script>
<canvas id="occChart" width="320"></canvas>
v3.x
Replacing postfix: '%' with following callback function:
options: {
...
plugins: { // toolip within plugin now
tooltip: { // before tooltips --> now toolip (singular)
usePointStyle: true,
// postfix: '%',
callbacks: { // <-- replacing 'postfix:'
label: function(context) {
return context.parsed.y + '%' || '';
}
}
}
...
}
See following complete code for v3.x and Run code snippet to see result:
const popCanvasName = document.getElementById('occChart').getContext('2d');
let myData = [];
let myLabels = [];
const myOccupancy = { // <-- let's use sample data meanwhile
"LabelList" : ["2021-08-02","2021-08-03","2021-08-04","2021-08-05","2021-08-06"],
"DataList" : [39,41,42,30,21]
};
function showChart() {
myData = myOccupancy.DataList;
myLabels = myOccupancy.LabelList;
// console.log(myData);
// console.log(myLabels);
const barChartName = new Chart(popCanvasName, {
type: 'line',
data: {
labels: myLabels,
datasets: [{
data: myData,
backgroundColor: ['rgba(55, 125, 255, 0.5)', 'rgba(255, 255, 255, 0.5)'],
fill: true, // <-- to show backgroundColor
borderColor: '#377dff',
borderWidth: 2,
pointRadius: 0,
pointHoverRadius: 0
}]
},
options: {
aspectRatio: 5,
responsive: true,
interaction: { // before hover --> now 'interaction'
intersect: false,
mode: 'nearest'
},
scales: {
yAxes: { // before '[{' now '{' (not an array anymore)
display: false
},
xAxes: { // before '[{' --> now '{' (not an array anymore)
type: 'time', // load moment.js and adapter for this to work
display: false,
time: {
unit: 'week',
displayFormats: {
hour: 'h:mm a',
day: 'ddd',
week: 'dddd',
month: 'MMM'
},
tooltipFormat: 'dddd, MMM DD, YYYY' // modify format string to your needs
}
}
},
plugins: {
tooltip: { // before tooltips --> now toolip (singular) within plugin
usePointStyle: true,
// postfix: '%',
callbacks: { // <-- replacing 'postfix:'
label: function(context) {
return context.parsed.y + '%' || '';
}
},
hasIndicator: true,
intersect: false
},
legend: { // --> now within plugin
display: false
}
}
}
});
};
function getChartData() {
return fetch('./Index?handler=OccupancyChartData', {
method: 'get',
headers: {
'Content-Type': 'application/json;charset=UTF-8'
}
})
.then(function(response) {
console.log(response);
if (response.ok) {
return response.text();
} else {
throw Error('Response Not OK');
}
})
.then(function(text) {
try {
return JSON.parse(text);
} catch (err) {
throw Error('Method Not Found');
}
})
.then(function(responseJSON) {
myOccupancy = responseJSON;
showChart();
});
};
showChart();
/* We use sample data meanwhile
$(document).on('ready', function() {
// getChartData(); <-- we use sample data meanwhile
// initialization of circles
$('.js-circle').each(function() {
var circle = $.HSCore.components.HSCircles.init($(this));
});
$('.js-chart').each(function () {
var chart = $.HSCore.components.HSChartJS.init($(this));
});
});
*/
<!-- get latest version of Chart.js, now at v3.5.1 -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<!-- You need moment.js and adapter for time to work at x-Axis -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-moment"></script>
<canvas id="occChart" width="320"></canvas>

Related

How to provide different labels in chart.js for toolbox and axis

I've provide a simple line chart with chart.js 3.7.0. How can I provide different labels for axis and toolbox? In my example I like to give empty lables besides 3 special values for the axis but the exact date value in the toolbox of a point.
My build:
<script>
chartLabels = ['2 years ago','', ... , '','1 year ago','', ... ,'','Today'];
chartData = [0,0, ... ,0,0.13,0.08, ... ,0,0.1];
yMax = 3;
</script>
<canvas id="chart-myvalues" width="160" height="90"></canvas>
In JS additionally:
const data = {
labels: chartLabels,
datasets: [{
label: 'My Value XYZ',
data: chartData,
tension: 0.5,
}]
};
const config = {
type: 'line',
data: data,
options: {
plugins: {
legend: {
display: false
}
},
scales: {
x: {
grid: {
display: false
},
ticks: {
autoSkip: false,
maxRotation: 0,
minRotation: 0
}
},
y: {
min: 0,
max: yMax,
grid: {
display: false
}
}
}
}
};
new Chart('chart-myvalue',config);
As asked for here is what I want exactly: In the screenshot above you see the 1 year ago once on the x axis and in the toolbox. On the x axis it is like I want it to. In the Toolbox I like to see the exact date of that value xyz (I can provide the date but I need to know how to provide different labels in chart.js for toolbox and axis)
It's called a tooltip and you can read more about it here. Basically, you have to make a callback to the title and label to change the x-axis and y-axis of the tooltip respectively. Here's how it would look:
boxLabels = ['2020-05-26', '2020-08-26', '2020-11-26', '2021-02-26', '2021-05-26', '2021-08-26', '2021-11-26', '2022-02-26', '2022-05-26'];
options: {
plugins: {
tooltip: {
callbacks: {
title: function(context) {
let title = context[0].label || boxLabels[context[0].dataIndex];
return title;
},
label: function(context) {
let label = context.dataset.label + ": " + context.dataset.data[context.datasetIndex];
return label;
}
}
}
}
};
Note that context for title returns an array, so you have to index it to get the element. See the snippet bellow for a whole example.
chartLabels = ['2 years ago','','','','1 year ago','','','','Today'];
chartData = [0,0,0,0,0.13,0.08,0,0,0.1];
yMax = 3;
boxLabels = ['2020-05-26', '2020-08-26', '2020-11-26', '2021-02-26', '2021-05-26', '2021-08-26', '2021-11-26', '2022-02-26', '2022-05-26'];
const data = {
labels: chartLabels,
datasets: [{
label: 'My Value XYZ',
data: chartData,
tension: 0.5,
}]
};
const config = {
type: 'line',
data: data,
options: {
plugins: {
legend: {
display: false
},
tooltip: {
callbacks: {
title: function(context) {
let title = context[0].label || boxLabels[context[0].dataIndex];
return title;
},
label: function(context) {
let label = context.dataset.label + ": " + context.dataset.data[context.datasetIndex];
return label;
}
}
},
},
scales: {
x: {
grid: {
display: false
},
ticks: {
autoSkip: false,
maxRotation: 0,
minRotation: 0
}
},
y: {
min: 0,
max: yMax,
grid: {
display: false
}
}
}
}
};
new Chart('chart-myvalues',config);
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<canvas id="chart-myvalues" width="160" height="90"></canvas>
<script src="https://cdn.jsdelivr.net/npm/chart.js#3.7.1/dist/chart.min.js"></script>
</body>
</html>

replace one amchart with another

Currently, I have this amchart below.
And I want to create another amchart with the same values. (I just want to replace the graph).
The new graphic is here -> https://www.amcharts.com/demos/line-graph/?theme=material#code
my code Angular:
prepareDataForTemplate(res) {
this.showLineChart = false;
if (res.RETURNCODE == 'OKK00') {
this.lines = [];
this.dataForChart.data.splice(0, this.dataForChart.data.length);
this.dataForChart.date.splice(0, this.dataForChart.date.length);
this.dataForChart.data.push(...res.HISTDEV.VALUE.map(x => x.COURS));
this.dataForChart.date.push(...res.HISTDEV.VALUE.map(x => x.DATE));
this.showLineChart = true;
if (res.HISTDEV.VALUE.length > 0) {
this.yMin = res.HISTDEV.VALUE[0].COURS;
this.yMax = res.HISTDEV.VALUE[0].COURS;
res.HISTDEV.VALUE.map(value => {
if (value.COURS < this.yMin) {
this.yMin = value.COURS;
}
if (value.COURS > this.yMax) {
this.yMax = value.COURS;
}
})
}
this.loadChart();
} else {
}
}
Then, the method loadChart(), it is the graph that I want to change...
loadChart() {
let datePipe = this.datePipe;
let decimalPipe = this.decimalPipe;
let leleuxNumPipe = this.leleuxNumPipe;
this.lineChartReturn = {
tooltip: {
trigger: 'axis',
position: function(pt) {
return [pt[0], '10%'];
},
formatter: function(params) {
return datePipe.transform(params[0].name) + "<br/>" +
params[0].marker + " " +
params[0].seriesName + " <b>" +
leleuxNumPipe.transform(decimalPipe.transform(params[0].value, '1.2-2')) + "</b";
}
},
title: {
left: 'center',
text: '',
},
xAxis: {
type: 'category',
boundaryGap: false,
//show: true,
data: this.dataForChart.date,
axisLabel: {
formatter: function(value, index) {
return datePipe.transform(value);
}
}
},
yAxis: {
type: 'value',
min: this.yMin,
max: this.yMax,
//show: true
axisLabel: {
formatter: function(value, index) {
return leleuxNumPipe.transform(decimalPipe.transform(value, '1.2-2'))
}
}
},
dataZoom: [{
type: 'inside',
start: 0,
end: 100
}, {
start: 0,
end: 10,
handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
handleSize: '80%',
handleStyle: {
color: '#fff',
shadowBlur: 3,
shadowColor: 'rgba(0, 0, 0, 0.6)',
shadowOffsetX: 2,
shadowOffsetY: 2
}
}],
series: [{
name: 'Amount',
type: 'line',
smooth: true,
symbol: 'none',
sampling: 'average',
itemStyle: {
color: 'rgba(255, 152, 0, .6)', // 'rgb(255, 70, 131)'
},
areaStyle: {
color: 'rgba(255, 152, 0, 0.15)',
origin: 'start'
},
lineStyle: {
// width: 1,
color: 'rgba(255, 152, 0, .6)',
},
data: this.dataForChart.data,
}, ]
};
}
In the doc amchart -> https://www.amcharts.com/demos/line-graph/?theme=material#code
I don't understand how to I adapt the code from amcharts with my method loadchart() ?
Sorry, if I ask you a lot
I'm pretty new to amcharts myself, but I'll give it a try.
First, I'm assuming that if you have a chart that you want to replace, you can save a reference to it, that would look something like this:
private chart: am4charts.XYChart;
And when you create your chart for the first time, wherever it is, you can do somthing like this:
this.chart = am4core.createFromConfig(this.lineChartReturn, 'htmlIdReference', am4charts.XYChart);
If your setup looks something like that, then you should be able to just use the dispose function, and then create it again with the new lineChartReturn you generate in loadChart
loadChart() {
if (this.chart) {
this.chart.dispose();
}
// your current code to generate new this.lineChartReturn
// Then just create it again using the createFromConfig
this.chart = am4core.createFromConfig(this.lineChartReturn, 'htmlIdReference', am4charts.XYChart);
}

How to hide the legend in chart.js in a react project?

I am trying to hide the legend of my chart created with Chart.js.
According to the official documentation (https://www.chartjs.org/docs/latest/configuration/legend.html), to hide the legend, the display property of the options.display object must be set to false.
I have tried to do it in the following way:
const options = {
legend: {
display: false,
}
};
But it doesn't work, my legend is still there. I even tried this other way, but unfortunately, without success.
const options = {
legend: {
display: false,
labels: {
display: false
}
}
}
};
This is my full code.
import React, { useEffect, useState } from 'react';
import { Line } from "react-chartjs-2";
import numeral from 'numeral';
const options = {
legend: {
display: false,
},
elements: {
point: {
radius: 1,
},
},
maintainAspectRatio: false,
tooltips: {
mode: "index",
intersect: false,
callbacks: {
label: function (tooltipItem, data) {
return numeral(tooltipItem.value).format("+0,000");
},
},
},
scales: {
xAxes: [
{
type: "time",
time: {
format: "DD/MM/YY",
tooltipFormat: "ll",
},
},
],
yAxes: [
{
gridLines: {
display: false,
},
ticks: {
callback: function(value, index, values) {
return numeral(value).format("0a");
},
},
},
],
},
};
const buildChartData = (data, casesType = "cases") => {
let chartData = [];
let lastDataPoint;
for(let date in data.cases) {
if (lastDataPoint) {
let newDataPoint = {
x: date,
y: data[casesType][date] - lastDataPoint
}
chartData.push(newDataPoint);
}
lastDataPoint = data[casesType][date];
}
return chartData;
};
function LineGraph({ casesType }) {
const [data, setData] = useState({});
useEffect(() => {
const fetchData = async() => {
await fetch("https://disease.sh/v3/covid-19/historical/all?lastdays=120")
.then ((response) => {
return response.json();
})
.then((data) => {
let chartData = buildChartData(data, casesType);
setData(chartData);
});
};
fetchData();
}, [casesType]);
return (
<div>
{data?.length > 0 && (
<Line
data={{
datasets: [
{
backgroundColor: "rgba(204, 16, 52, 0.5)",
borderColor: "#CC1034",
data: data
},
],
}}
options={options}
/>
)}
</div>
);
}
export default LineGraph;
Could someone help me? Thank you in advance!
PD: Maybe is useful to try to find a solution, but I get 'undefined' in the text of my legend and when I try to change the text like this, the text legend still appearing as 'Undefindex'.
const options = {
legend: {
display: true,
text: 'Hello!'
}
};
As described in the documentation you linked the namespace where the legend is configured is: options.plugins.legend, if you put it there it will work:
var options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderColor: 'pink'
}
]
},
options: {
plugins: {
legend: {
display: false
}
}
}
}
var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.0/chart.js"></script>
</body>
On another note, a big part of your options object is wrong, its in V2 syntax while you are using v3, please take a look at the migration guide
Reason why you get undefined as text in your legend is, is because you dont supply any label argument in your dataset.
in the newest versions this code works fine
const options = {
plugins: {
legend: {
display: false,
},
},
};
return <Doughnut data={data} options={options} />;
Import your options value inside the charts component like so:
const options = {
legend: {
display: false
}
};
<Line data={data} options={options} />

append API data into an array

I need to display apex chart (Brush Chart). I am trying to append data from API into Array. i have given code below and also API data.
I used console to check that the data is coming correctly from API but not appending to series array
<div id="app" style="background:white">
<div id="chart1">
<apexchart type=line height=230 :options="chartOptionsArea" :series="series" />
</div>
<div id="chart2">
<apexchart type=area height=130 :options="chartOptionsBrush" :series="series" />
</div>
</div>
below is my VUEjs code
data() {
return {
series: [{
data: this.generateDayWiseTimeSeries(new Date('01 Jan
2014 ').getTime(),185, {
min: 30,
max: 90
})
}],
chartOptionsArea: {
chart: {
id: 'chartArea',
toolbar: {
autoSelected: 'pan',
show: false
}
},
colors: ['#546E7A'],
stroke: {
width: 3
},
dataLabels: {
enabled: false
},
fill: {
opacity: 1,
},
markers: {
size: 0
},
xaxis: {
type: 'datetime'
}
},
chartOptionsBrush: {
chart: {
id: 'chartBrush',
brush: {
target: 'chartArea',
enabled: true
},
selection: {
enabled: true,
xaxis: {
min: new Date('01 Jan 2014').getTime(),
max: new Date('09 Jan 2014').getTime()
}
},
},
colors: ['#008FFB'],
fill: {
type: 'gradient',
gradient: {
opacityFrom: 0.91,
opacityTo: 0.1,
}
},
xaxis: {
type: 'datetime',
tooltip: {
enabled: false
}
},
yaxis: {
tickAmount: 2
}
}
}
}
below is Function
generateDayWiseTimeSeries: function() {
var i = 0;
var self = this;
var series;
axios
.get("http://172.31.0.114:5000/api/eco/BNG-JAY-136-001")
.then(function(res) {
self.series = res.data; //not working
})
return series;
}
API data
[
[
"2019-5-23",
0
],
[
"2019-5-24",
0
],
[
"2019-5-25",
0
],
[
"2019-5-26",
0
],
[
"2019-5-27",
0
],
[
"2019-5-28",
0
],
[
"2019-5-29",
0
],
[
"2019-5-30",
0
],
[
"2019-5-31",
0
]
]
You can use updateSeries method or you can directly update the value of series. Please check below code
Code Snippet
generateDayWiseTimeSeries: function() {
var me = this;
axios.get("data.json")
.then(function(res) {
me.series[0].data = res.data;
//OR you can use updateSeries method
/* me.$children[0].updateSeries([{
data: res.data
}]);*/
});
return [];
}
You can check here with working fiddle.
generateDayWiseTimeSeries function return undefined variable => series.
Assign returned data to series instead of self.series.

How to display different tooltip based on data values in ChartJS v2?

I’m using ChartJs, to display a Line chart and I’m trying to do 2 things :
The first one is to display different colors based on the tooltip’s value. Highest value vs Medium value
The second one is to display a different tooltip if the tooltips value is the lowest. Minimun value
I’ve tried to use a custom plugins to do this, but It didn’t work
This is the code I've managed to do so far :
Chart.plugins.register({
beforeRender: function(chart) {
if (chart.config.options.showAllTooltips) {
chart.pluginTooltips = [];
chart.config.data.datasets.forEach(function(dataset, i) {
chart.getDatasetMeta(i).data.forEach(function(sector, j) {
console.log(j, sector);
chart.pluginTooltips.push(
new Chart.Tooltip(
{
_chart: chart.chart,
_chartInstance: chart,
_data: chart.data,
_options: chart.options.tooltips,
_active: [sector],
},
chart
)
);
});
});
// turn off normal tooltips
chart.options.tooltips.enabled = false;
}
},
afterDraw: function(chart, easing) {
if (chart.config.options.showAllTooltips) {
if (!chart.allTooltipsOnce) {
if (easing !== 1) return;
chart.allTooltipsOnce = true;
}
// turn on tooltips
chart.options.tooltips.enabled = true;
Chart.helpers.each(chart.pluginTooltips, function(tooltip) {
tooltip.initialize();
tooltip._options.bodyFontFamily = "Visby";
// Change color based on value
tooltip._options.bodyFontColor = '#FEB122';
// Change tooltip's html if minimun value of dataset
// Values .datapoints[0].value
// console.log(tooltip._model);
tooltip._options.displayColors = false;
tooltip._options.bodyFontSize = tooltip._chart.height * 0.05;
tooltip._options.yPadding = 0;
tooltip._options.xPadding = 0;
tooltip.update();
tooltip.pivot();
tooltip.transition(easing).draw();
});
chart.options.tooltips.enabled = false;
}
}
});
let canvas = document.getElementById("myLineChart");
Chart.defaults.global.defaultFontFamily = "Visby";
const ctx = canvas.getContext('2d');
const labels = JSON.parse(ctx.canvas.dataset.dates);
const prices = JSON.parse(ctx.canvas.dataset.prices);
const myLineChart = new Chart(ctx, {
type: 'line',
data: {
labels: labels,
datasets: [{
label: "Prix du billet",
data: prices,
backgroundColor: [
'rgba(0, 0, 0, 0)',
],
borderColor: [
'#F2F2F2',
],
pointBackgroundColor:
'#FEB122',
pointBorderColor:
'#FEB122',
borderWidth: 3,
}]
},
options: {
showAllTooltips: true, // call plugin we created
responsive: true,
cutoutPercentage: 60,
legend: {
position: "bottom"
},
animation: {
animateScale: true,
animateRotate: true
},
tooltips: {
enabled: false,
backgroundColor:"rgba(0,0,0,0)",
callbacks: {
title: function(tooltipItems, data) {
return "";
},
label: function(tooltipItem, data) {
var datasetLabel = "";
var label = data.labels[tooltipItem.index];
return data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index] + '€';
},
labelColor: function(tooltipItem, data) {
// console.log(data);
}
}
},
legend: {
display: false
},
layout: {
padding: {
left: 32,
right: 32,
top: 32,
bottom: 32
}
},
scales: {
xAxes: [{
gridLines: {
display: false,
drawBorder: false,
},
}],
yAxes: [{
display: false
}]
}
}
});
How could I make this work ?
I've managed to do that by using the plugin Chartjs Datalabels.
And using the scriptable colors options.

Categories

Resources