I'm having a hard time creating my first plugin for chart.js
After watching a few tutorials, I made the code below expecting to get "chart" in the console but nothing happens.
What am I missing here?
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdn.jsdelivr.net/npm/chart.js#4.1.1/dist/chart.umd.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-annotation#2.1.1/dist/chartjs-plugin-annotation.min.js"></script>
</head>
<body>
<div>
<canvas id="myChart"></canvas>
</div>
<script>
const ctx = document.getElementById('myChart');
const tooltipNote = {
id: 'tooltipNote',
beforeDraw: chart => {
console.log('chart');
}
}
new Chart(ctx, {
type: 'line',
responsive: true,
data: {
labels: ['', '', '', '', '', ''],
datasets: [{
data: [42, 119, 53, 55, 62, 53],
}]
},
options: {
scales: {
y: {
suggestedMin: 0,
offset: true
},
},
plugins: {
legend: {
display: false
},
tooltipNote: {
},
},
},
});
</script>
</body>
</html>
You never register your plugin as documented here: https://www.chartjs.org/docs/latest/developers/plugins.html
You can either only register it specific chart instances like so:
const tooltipNote = {
id: 'tooltipNote',
beforeDraw: chart => {
console.log('chart');
}
};
new Chart(ctx, {
data: data,
options: options,
plugins: [tooltip note]
});
Or you can register it globally so it is available to all your instances:
const tooltipNote = {
id: 'tooltipNote',
beforeDraw: chart => {
console.log('chart');
}
}
Chart.register(tooltipNote);
What you did was only define the options as an empty object for your plugin.
Related
I want to display values with predefined units. e.g.: 22.00B/s
The data structure looks like this:
['6.84KB/s', '4.49KB/s', '3.42KB/s']
But only such data are displayed:
['7.5', '4.3', '10.3']
How can I display such values?
3.42KB/s
(Without removing letters or special characters)
You will need to use a category scale for this:
const options = {
type: 'bar',
data: {
labels: ["val1", "val2", "val3"],
datasets: [{
label: '# of Votes',
data: ['6.84KB/s', '4.49KB/s', '3.42KB/s'],
backgroundColor: 'pink'
}]
},
options: {
scales: {
y: {
type: 'category',
labels: ['6.84KB/s', '4.49KB/s', '3.42KB/s'],
reverse: true
}
}
}
}
const 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.8.2/chart.js"></script>
</body>
I'm trying to adapt https://www.chartjs.org/docs/latest/samples/bar/floating.html to create a kind of timeline chart, where the horizontal axis (the range data) are timestamps. Unfortunately I can't seem to get the data to display, and don't see any error messages, etc.
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/moment#^2"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js#^3"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-moment#^1"></script>
</head>
<body>
<div>
<canvas id="myChart"></canvas>
</div>
</body>
<script>
//const labels = ["a","b","c","d","fff","g","h"]
const labels = ["a","b"]
const data = {
labels: labels,
datasets: [
{
label: 'Dataset 1',
data: [[moment("2021-11-23T00:24:14Z"),moment("2021-11-23T00:34:03Z")],
[moment("2021-11-23T00:24:14Z"),moment("2021-11-23T00:26:35Z")]]
// This works fine (without 'yAxes' below):
//data: labels.map(() => {
//return [Math.random(), Math.random()];
//}),
//backgroundColor: Utils.CHART_COLORS.red,
},
]
};
const config = {
type: 'bar',
data: data,
options: {
yAxes: [{
type: 'time',
}],
indexAxis: 'y',
responsive: true,
plugins: {
legend: {
position: 'top',
},
title: {
display: true,
text: 'Chart.js Floating Bar Chart'
}
}
}
};
var ctx = document.getElementById("myChart").getContext("2d");
new Chart(ctx, config);
</script>
</html>
EDIT: JSFiddle: https://jsfiddle.net/r5ypuvks/
Mmm it seems my issues are:
not using proper axis format for chart.js 3
need to scale the graph myself
need to refer to horizontal axis as x
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/moment#^2"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js#^3"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-moment#^1"></script>
</head>
<body>
<div>
<canvas id="myChart"></canvas>
</div>
</body>
<script>
//const labels = ["a","b","c","d","fff","g","h"]
const labels = ["a","b"]
const data = {
labels: labels,
datasets: [
{
label: 'Dataset 1',
data: [[("2021-11-23T00:24:14Z"),("2021-11-23T00:34:03Z")],
[("2021-11-23T00:25:14Z"),("2021-11-23T00:26:35Z")]]
// This works fine (without 'yAxes' below):
//data: labels.map(() => {
//return [Math.random(), Math.random()];
//}),
//backgroundColor: Utils.CHART_COLORS.red,
},
]
};
const config = {
type: 'bar',
data: data,
options: {
scales: {
x: {
min: ("2021-11-23T00:20:14Z"),
max: ("2021-11-23T00:44:14Z") ,
type: 'time',
},
},
indexAxis: 'y',
responsive: true,
plugins: {
legend: {
position: 'top',
},
title: {
display: true,
text: 'Chart.js Floating Bar Chart'
}
}
}
};
var ctx = document.getElementById("myChart").getContext("2d");
new Chart(ctx, config);
</script>
</html>
I am trying to use the custom tooltip from Apex Charts, have tried multiple examples online but they dont seem to work.. I am getting a tool tip but it seems like its the standard tooltip.
const { _getSum } = require("../helper/dynamicFormat");
const express = require("express");
const router = express.Router();
const { Validator } = require("../middlewares");
const resolvers = require("../resolvers");
const db = require("../models");
const moment = require("moment");
const _ = require("lodash");
const { getRandomColors } = require("../helper/colors");
router.get(
"/",
[Validator.check("query").not().isEmpty()],
Validator,
async (req, res, next) => {
try {
const { query } = req.query;
const options = JSON.parse(query);
let idleData=[
{
x: '3R4785',
y: [
new Date(1789, 3, 1,18,30).getTime(),
new Date(1789, 3, 1,19,30).getTime(),
]},{
x: '3R4785',
y: [
new Date(1789, 3, 1,21).getTime(),
new Date(1789, 3, 1,22).getTime(),
]
}
]
let drivingData= [
{
x: '3R4785',
y: [
new Date(1789, 3, 1,22).getTime(),
new Date(1789, 3, 1,23).getTime()
]
},
]
let parkingData=[
{
x: '3R4785',
y: [
new Date(1789, 3, 1, 23).getTime(),
new Date(1789, 3, 1,24).getTime(),
]
},
]
res.render("millage", {
options: JSON.stringify({
series: [
{
name: 'Idle',
data:idleData
},
{
name: 'Driving',
data:drivingData
},
{
name: 'Parking',
data: parkingData
},
],
chart: {
height: 350,
type: 'rangeBar'
},
plotOptions: {
bar: {
horizontal: true,
barHeight: '50%',
rangeBarGroupRows: true
}
},
colors: [
"#008FFB", "#00E396", "#FEB019", "#FF4560", "#775DD0",
"#3F51B5", "#546E7A", "#D4526E", "#8D5B4C", "#F86624",
"#D7263D", "#1B998B", "#2E294E", "#F46036", "#E2C044"
],
fill: {
type: 'solid'
},
xaxis: {
type: 'datetime',
format: 'hh mm'
},
tooltip: {
custom: function({series, seriesIndex, dataPointIndex, w}) {
var data = w.globals.initialSeries[seriesIndex].data[dataPointIndex];
console.log("tooltip",series,seriesIndex,dataPointIndex,w)
return '<ul>' +
'<li><b>Price</b>: ' + data.x + '</li>' +
'<li><b>Number</b>: ' + data.y + '</li>' +
'</ul>';
}
},
legend: {
position: 'right'
},
}),
});
} catch (error) {
console.log("🚀 ~ file: millage.js ~ line 13 ~ error", error);
}
}
);
module.exports = router;
I have tried multiple examples online, but nothing changes the standard tooltip.. I get a tooltip but it's not the one I want. Also when I try to console out the tooltip function, nothing comes..
I tried also made sure to use the latest apext charts
this is how I render the component:-
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0">
<script src="https://cdn.jsdelivr.net/npm/apexcharts#latest"></script>
</head>
<body>
{{{body}}}
</body>
</html>
<div id="chart"></div>
<script>
const defaultOptions = {
}
const options = JSON.parse(`{{options}}`.replace(/"/g, '"'));
var chart = new ApexCharts(document.getElementById("chart"), { ...defaultOptions, ...options });
chart.render();
</script>
I just can't figure out why is there allways at least one category missing from my chart:
This does not happen when I switch chart type to type:'pie'.
Please find my code below:
<!DOCTYPE html>
<html>
<body>
<div style="width: 40%;">
<canvas id="polarAreaChart " width="400" height="400"></canvas>
</div>
<script>
var ctx = document.getElementById("polarAreaChart ");
var polarAreaChart = new Chart(ctx, {
type: 'polarArea',
options: {
legend: {
display: true,
position: 'bottom',
}
},
data: {
labels: ["D1","D2","D3"],
datasets: [{
label: 'Dimensiones',
data: [40, 20, 40],
backgroundColor: [
"#f8b195",
"#c06c84",
"#6c5b7b"
]
}]
}
});
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.4/Chart.bundle.min.js"></script>
</body>
</html>
Any comments will help.
Cheers!
Apparently it was just a bug.
Solved it by using a more recent version of Chartjs:
https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.bundle.min.js
I am using the canvasjs for plotting the column chart. I am using the code from this link https://canvasjs.com/editor/?id=https://canvasjs.com/example/gallery/column/oil_reserves/, the code is below:
<!DOCTYPE HTML>
<html>
<head>
<title>Basic HTML5 Column Chart </title>
<script type="text/javascript">
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer",
{
title:{
text: "Top Oil Reserves"
},
animationEnabled: true,
axisY: {
title: "Reserves(MMbbl)"
},
legend: {
verticalAlign: "bottom",
horizontalAlign: "center"
},
theme: "theme2",
data: [
{
type: "column",
showInLegend: true,
legendMarkerColor: "grey",
legendText: "MMbbl = one million barrels",
dataPoints: [
{y: 297571, label: "Venezuela"},
{y: 267017, label: "Saudi" },
{y: 175200, label: "Canada"},
{y: 154580, label: "Iran"},
{y: 116000, label: "Russia"},
{y: 97800, label: "UAE"},
{y: 20682, label: "US"},
{y: 20350, label: "China"}
]
}
]
});
chart.render();
}
</script>
<script type="text/javascript" src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
</head>
<body>
<div id="chartContainer" style="height: 300px; width: 100%;">
</div>
</body>
</html>
Now I want to use a text file generated from python instead of the default values in the dataPoints. The test file data looks like a dictionary data separated by comma. Here is a sample of the text file data:
{'DNS_SERVER1': 2.768651, 'FTP_SERVER1': 2.488129, 'AUTHENTICATION_SERVER1': 2.768651, 'WAP_SERVER1': 2.768651, 'WEB_SERVER1': 2.768651, 'EMAIL_SERVER1': 2.768651}
I want the labels to be first part before semicolon like 'DNS_SERVER1' and the value y to be equal to 2nd part of the semicolon like 2.768651. How Can I do this using the canvasjs script? Any help is appreciated.
Thanks.
You must have to read the file to two separate datasets (LABELS and DATA) and insert them like this:
data = {
labels: ["DNS_SERVER", "FTP_SERVER", "AUTH_SERVER"],
datasets: [{
label: 'Performance',
data: [2.768651, 2.488129, 2.768651]
}]
};
Above is a nominal way.
You can change "labels:" dataset and "data:" dataset for your loaded data.