How to create logarithmic scale in chart.js with normal numbers? - javascript

How to create a chart.js with logarithmic scale on xAxis with normal numbers instead of "1e+0" etc.? Here's my code:
/* eslint-disable */
import { Line, mixins } from 'vue-chartjs';
Chart.plugins.register({
beforeDraw: function (chartInstance) {
const { ctx } = chartInstance.chart;
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, chartInstance.chart.width, chartInstance.chart.height);
}
});
const { reactiveProp } = mixins;
export default {
extends: Line,
mixins: [reactiveProp],
data() {
return {
options: {
maintainAspectRatio: false,
responsive: true,
legend: {
display: false,
position: 'bottom',
},
scales: {
yAxes: [
{
ticks: {
suggestedMin: 0,
callback(tick) {
return `${tick}%`;
},
},
},
],
xAxes: [
{
display: true,
type: "logarithmic",
}
]
},
tooltips: {
callbacks: {
label(tooltipItem, data) {
const dataset = data.datasets[tooltipItem.datasetIndex];
const currentValue = dataset.data[tooltipItem.index];
return `${currentValue} %`;
},
},
},
},
};
},
mounted() {
this.renderChart(this.chartData, this.options);
},
};
/* eslint-enable */
And mine chart:
Appearently all the values are on the same x dont konw why also. Version of chart.js: 2.9.3 (it cannot be changed). Thanks for any advice and help!

You can use the tick callback to transfrom it to a normal number again:
var options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderColor: 'blue'
}]
},
options: {
scales: {
yAxes: [{
type: 'logarithmic',
ticks: {
callback: (val) => (val)
}
}]
}
}
}
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/2.9.4/Chart.js"></script>
</body>

Related

how to properly implement crosshair plugin with vue chartjs? - keep getting Cannot read properties of undefined error (reading 'dragStarted')

I'm struggling with setting chartjs-plugin-crosshair to work with my chart (chartjs).
Project dependencies are:
vue-chartjs: 4.1.0
chartjs-plugin-crosshair: 1.2.0
chart.js: 3.7.1
i'm getting errors:
first:
Uncaught TypeError: Cannot read properties of undefined (reading 'dragStarted')
then (on mouse move over chart):
Uncaught TypeError: Cannot read properties of undefined (reading 'length')
My component:
<template>
<Line :chart-data="chartData" :plugins="[CrosshairPlugin]" :chart-options="chartOptions" ref="myChart" />
</template
<script setup>
import { Line } from 'vue-chartjs'
import { Chart as ChartJS, Title, Tooltip, Legend, PointElement, LineElement, CategoryScale, LinearScale, TimeSeriesScale } from 'chart.js'
import {CrosshairPlugin,Interpolate} from 'chartjs-plugin-crosshair';
ChartJS.register(Title, Tooltip, Legend, PointElement, LineElement, CategoryScale, LinearScale, TimeSeriesScale)
const myChart = ref();
const chartData ={
labels: [1,2,3,4],
datasets: [{label:'test', data:[51,52,53,54],borderWidth:1, borderColor:'#f0f'}]
}
const chartOptions = {
interaction: {
mode: 'nearest'
},
scales: {
xAxes: {
stacked:true,
grid: {
color:"rgba(80,201,209,.3)",
borderColor:"rgba(80,201,209,1)"
},
title: {
display:true,
text: 'value'
},
ticks: {
color:"rgba(80,201,209,1)"
source: 'labels',
},
},
yAxes: {
grid: {
color:"rgba(80,201,209,.3)",
borderColor:"rgba(80,201,209,1)"
},
title: {
display: false,
},
ticks: {
color:rgba(80,201,209,1),
},
},
},
plugins: {
crosshair:
{
sync: {
enabled: false
},
zoom: {
enabled: false
},
snap: {
enabled: true
}
}
}
}
can anyone help?
This is because you gave your scales a custom ID, setting them back to the default x and y (by changing the object keys from yAxes to y and from xAxes to x) will resolve your issue:
const options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderColor: 'pink'
},
{
label: '# of Points',
data: [7, 11, 5, 8, 3, 7],
borderColor: 'orange'
}
]
},
options: {
hover: {
intersect: false
},
scales: {
x: {
stacked: true,
grid: {
color: "rgba(80,201,209,.3)",
borderColor: "rgba(80,201,209,1)"
},
title: {
display: true,
text: 'value'
},
ticks: {
color: "rgba(80,201,209,1)",
source: 'labels',
},
},
y: {
grid: {
color: "rgba(80,201,209,.3)",
borderColor: "rgba(80,201,209,1)"
},
title: {
display: false,
},
ticks: {
color: 'rgba(80, 201, 209, 1)',
},
},
},
plugins: {
crosshair: {
sync: {
enabled: false
},
zoom: {
enabled: false
},
snap: {
enabled: 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.0/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-crosshair"></script>
</body>

How to adjust spaces between points in chart js?

I am trying to make a line chart by using chart.js. But I facing a problem. I want to control the space between points, but the chart.js makes it equal.
Here is my code:
<canvas id="myChart"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.js" integrity="sha512-OD9Gn6cAUQezuljS6411uRFr84pkrCtw23Hl5TYzmGyD0YcunJIPSBDzrV8EeCiFxGWWvtJOfVo5pOgB++Jsag==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script>
var ctx = document.getElementById("myChart");
var points = [1,1,9,9.3];
var Dates = ["Dec 29th", "jan 10th", "Feb 21st", "Feb 25th"];
var myChart = new Chart(ctx, {
type: "line",
data: {
labels: Dates,
datasets: [
{
label: "My chart",
data: points,
backgroundColor: "black",
borderColor: "blue",
borderWidth: 3,
fill: false,
lineTension: 0.4,
}
]
},
options: {
legend: {display: false},
scales: {
yAxes:[{
ticks: {
min:1,
max: 9.9,
callback: function(value, index, values) {
return '$' + value;
}
}
}],
},
elements: {
point:{
radius: 0
}
}
}
});
</script>
Here is the result of my code:
But I want the big space in middle like this:
How can I make the big space between point 3 and point4, please?
Can you use time on the x axis?
Below is an example
// "+" before (new Date(2021,11,29)) return miliseconds from 1970 year
const dataA = [
{x:+new Date(2021,11,29), y:1}, // { x: 1640732400000, y: 1},
{x:+new Date(2022,0,10), y:1}, // { x: 1641769200000, y: 1},
{x:+new Date(2022,1,21), y:9}, // { x: 1645398000000, y: 9},
{x:+new Date(2022,1,25), y:9.3}, // { x: 1645743600000, y: 9.3}
];
const cfgChart = {
type: 'line',
data: {
datasets: [
{
backgroundColor: '#74adf7',
borderColor: '#74adf7',
data: dataA,
label: 'A',
lineTension: 0.4,
},
],
},
options: {
animation: false,
parsing: false,
interaction: {
mode: 'index',
axis: 'x',
intersect: false,
},
scales: {
x: {
type: 'time',
},
},
},
};
const chart = new Chart(document.querySelector('#chart').getContext('2d'), cfgChart);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/2.3.1/luxon.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-adapter-luxon/1.1.0/chartjs-adapter-luxon.min.js"></script>
<div>
<canvas id="chart"></canvas>
</div>

Chart.js v3 - beginAtZero does nothing to my chart

I read many threads on the beginAtZero parameter in Chart.js, but none of the solutions I found actually work for me.
I have a simple line chart with dates on my x axe and integers in my y axe. I can't manage to make my y axe start with 0.
let atchoum = document.querySelector("#atchoum")
let statchoum = new Chart(atchoum, {
type: "line",
data: {
labels: {{ atchoumDate|raw }},
datasets: [{
label: "Nombre d'éternuements au support",
data: {{ atchoumNb|raw }},
borderColor: "blue",
tension: 0.3,
options: {
responsive: true,
scales: {
y: {
beginAtZero: true
}
},
animations: {
y: {
easing: 'easeInOutElastic',
from: (ctx) => {
if (ctx.type === 'data') {
if (ctx.mode === 'default' && !ctx.dropped) {
ctx.dropped = true;
return 0;
}
}
}
}
},
}
}]
}
})
You are defining your options in the dataset itself.
The options object is supposed to be on the same level as the type and data fields since the options are for the entire chart and not for a single dataset.
const options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 7, 9, 20, 8]
}]
},
options: {
scales: {
y: {
beginAtZero: 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.5.1/chart.js"></script>
</body>

How do you set x and y axis and Title for a line chart using charts.js?

This is using charts.js. This code only makes the line graph but the title, x axis and y axis does not show. I want to add title, and the names for those 2 axis onto the graph. what is wrong and how do you fix it? I also want to make the y axis to start from 0 and up.
async function chartDisplay() {
await getData1();
await getData2();
const ctx = document.getElementById('chart').getContext('2d');
const myChart = new Chart(ctx, {
type: 'line',
data: {
labels: xLabels,
datasets: [{
data: ratingDataI,
label: "data1",
borderColor: "#3E95CD",
fill: false
},
{
data: ratingDataA,
label: "data2",
borderColor: "#3E95CD",
fill: false
}
]
},
options: {
responsive: true,
title: {
display: true,
text: 'Chart.js Line Chart'
},
tooltips: {
mode: 'label',
},
hover: {
mode: 'nearest',
intersect: true
},
scales: {
x: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Dates'
}
}],
y: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Value'
}
}]
}
}
});
}
the x and y should not be arrays but objects, also the scaleLabel prop is called title now. For all the changes please read the migration guide (https://www.chartjs.org/docs/master/getting-started/v3-migration.html)
Example:
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: {
scales: {
y: {
beginAtZero: true,
title: {
display: true,
text: 'yAxis'
}
},
x: {
title: {
display: true,
text: 'xAxis'
}
}
}
}
}
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.4.1/chart.js"></script>
</body>

How to export Chart.js chart using toBase64Image, but with no transparency?

I have few charts in my application, created with Chart.js library. I need to export them and include in some kind of reports generated by my application. An example chart code is appended below:
export default {
extends: Line,
mixins: [reactiveProp],
data() {
return {
options: {
maintainAspectRatio: false,
responsive: true,
legend: {
display: true,
position: 'bottom',
},
scales: {
yAxes: [
{
ticks: {
suggestedMin: 0,
callback(tick) {
return `${tick}%`;
},
},
},
],
},
tooltips: {
callbacks: {
label(tooltipItem, data) {
const dataset = data.datasets[tooltipItem.datasetIndex];
const currentValue = dataset.data[tooltipItem.index];
return ` ${dataset.label}: ${currentValue}%`;
},
},
},
animation: {
// eslint-disable-next-line no-unused-vars
onComplete(animation) {
store.commit('myModule/myMutation', this.toBase64Image());
},
},
},
};
},
mounted() {
this.renderChart(this.chartData, this.options);
},
};
As you have noticed, i use onComplete to save the chart in my store. I call the function toBase64Image() there. An image is being saved almost properly, but the background is ignored, so the result is transparent. I would like to have the chart but with the white background after the serialization. Is it possible to achieve it? How can i solve this problem (I've tried to set the background color using the chart styles, but still serialization result is transparent)? Thanks for any help
This behaviour comes because there is nothing drawn on the chart as a background. This can be fixed with a custom inline plugin like so (fillStyle is the color of the background):
plugins: [{
id: 'custom_canvas_background_color',
beforeDraw: (chart) => {
const ctx = chart.canvas.getContext('2d');
ctx.save();
ctx.globalCompositeOperation = 'destination-over';
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, chart.canvas.width, chart.canvas.height);
ctx.restore();
}
}]
example:
var options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderWidth: 1
},
{
label: '# of Points',
data: [7, 11, 5, 8, 3, 7],
borderWidth: 1
}
]
},
options: {
scales: {
yAxes: [{
ticks: {
reverse: false
}
}]
}
},
plugins: [{
id: 'custom_canvas_background_color',
beforeDraw: (chart) => {
const ctx = chart.canvas.getContext('2d');
ctx.save();
ctx.globalCompositeOperation = 'destination-over';
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, chart.canvas.width, chart.canvas.height);
ctx.restore();
}
}]
}
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/2.9.4/Chart.js" integrity="sha512-hZf9Qhp3rlDJBvAKvmiG+goaaKRZA6LKUO35oK6EsM0/kjPK32Yw7URqrq3Q+Nvbbt8Usss+IekL7CRn83dYmw==" crossorigin="anonymous"></script>
</body>

Categories

Resources