React chart2js Line chart with multiple datasets overlapping - reactjs

chart
const data = {
labels: Array(coordinates.length).fill("l"),
datasets: buildDataset(),
options: {
animation: false,
scales: {
// ???????
},
legend: {
display: false
},
tooltips: {
callbacks: {
label: function(tooltipItem) {
return tooltipItem.yLabel;
}
}
},
maintainAspectRatio: false,
scales: {
myScale: {
position: 'left',
}
},
elements: {
point:{
radius: 0
}
}
}
}
return (
<Chart>
<Line
data={data}
width={50}
height={20}
options={data.options}>
</Line>
</Chart>
)
// ~~~~~
let obj = {
label: stops[0].miles == 0 ? index : index + 1,
data: points,
backgroundColor: colors[index],
tension: 0.4,
fill: true
}
These charts are built from an array of obj objects. The points variable that data refers is an array of object like: [{x: 0, y: 10257}, {x: 1, y: 10245}]
How do I get my line chart to display these different datasets side by side? I assume it has something to do with the scales parameter but wasn't able to find anything that worked in the docs.
Thanks!

For the object notation to work chart.js needs values to plot them against (not the index in the array) so you cant just provide an array containing only the value l.
You can either provide a labels array containing increasing numbers to which you match it or remove it and set your x scale to linear.
Labels example:
var options = {
type: 'line',
data: {
labels: [0, 1, 2, 3],
datasets: [{
label: '# of Votes',
data: [{
x: 0,
y: 4
}, {
x: 1,
y: 6
}, {
x: 2,
y: 2
}],
borderColor: 'pink'
},
{
label: '# of Points',
data: [{
x: 2,
y: 2
}, {
x: 3,
y: 3
}],
borderColor: 'blue'
}
]
},
options: {
scales: {}
}
}
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>
Linear example:
var options = {
type: 'line',
data: {
datasets: [{
label: '# of Votes',
data: [{
x: 0,
y: 4
}, {
x: 1,
y: 6
}, {
x: 2,
y: 2
}],
borderColor: 'pink'
},
{
label: '# of Points',
data: [{
x: 2,
y: 2
}, {
x: 3,
y: 3
}],
borderColor: 'blue'
}
]
},
options: {
scales: {
x: {
type: 'linear'
}
}
}
}
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>

Related

Cannot find a way to correctly use chartjs annotation plugin with react

I am currently trying to use the plugin chartjs-plugin-annotation in my react project.
Unfortunately, it is not working...
He is my implementation :
import React, { Component } from "react";
//import "./css/tideComponent.css";
import jsonData from "./ressources/tideOostende2023.json";
import "chart.js/auto";
import { Chart } from "react-chartjs-2";
import * as ChartAnnotation from "chartjs-plugin-annotation";
class Tide extends Component {
state = {
dayDate: new Date().toJSON().slice(5, 10),
highTide: "",
highTide2: "",
lowTide: "",
lowTide2: "",
};
async componentDidMount() {
const index = jsonData.findIndex(
(item) => item.date === this.state.dayDate
);
//TODO store tide in an array(using split method) & filter low to high to have a correct graph
this.setState({
highTide: jsonData[index].highTide,
highTide2: jsonData[index].highTide2,
lowTide: jsonData[index].lowTide,
lowTide2: jsonData[index].lowTide2,
});
}
timeToNumeric(tideTime) {
const tideTimeSplitted = tideTime.split(":");
return tideTimeSplitted[0] * 1 + tideTimeSplitted[1] / 60;
}
handleTideData() {
if (
this.timeToNumeric(this.state.highTide) <
this.timeToNumeric(this.state.lowTide)
)
return [
{ x: -2, y: 0.5 },
{ x: this.timeToNumeric(this.state.highTide), y: 1.5 },
{ x: this.timeToNumeric(this.state.lowTide), y: 0.5 },
{ x: this.timeToNumeric(this.state.highTide2), y: 1.5 },
{ x: this.timeToNumeric(this.state.lowTide2), y: 0.5 },
{ x: 26, y: 1.5 },
];
return [
{ x: -2, y: 1.5 },
{ x: this.timeToNumeric(this.state.lowTide), y: 0.5 },
{ x: this.timeToNumeric(this.state.highTide), y: 1.5 },
{ x: this.timeToNumeric(this.state.lowTide2), y: 0.5 },
{ x: this.timeToNumeric(this.state.highTide2), y: 1.5 },
{ x: 26, y: 0.5 },
];
}
render() {
const data = {
datasets: [
{
data: this.handleTideData(),
fill: false,
backgroundColor: "rgb(35, 71, 89, 0.88)",
borderColor: " rgb(35, 71, 79, 0.88)",
tension: 0.4,
},
],
};
const options = {
annotation: {
annotations: [
{
type: "line",
mode: "horizontal",
scaleID: "x",
value: 1,
borderColor: "white",
borderWidth: 2,
},
],
},
scales: {
x: { min: 0, max: 24, ticks: { stepSize: 1 } },
y: { min: 0, max: 2.2, display: false },
},
showLine: true,
pointStyle: false,
plugins: {
legend: { display: false },
},
};
return (
<div className="tideContainer">
<Chart
type="scatter"
data={data}
options={options}
plugins={ChartAnnotation}
/>
</div>
);
}
}
export default Tide;`
I tried different things but still not working. I also reviewed multiple question on SO but cannot find my solution. Chart Js is correctly working with my implementation, it is only the plugin that does not work.
Thank you in advance for your great help !!!
I think plugins property in react-chartjs-2 should be an array, I guess.
<Chart
type="scatter"
data={data}
options={options}
plugins={[ChartAnnotation]}
/>
The options config for annotation plugin is not in the right node.
It must be added in options.plugins node.
const options = {
plugins: { // <-- to add, was missing
annotation: {
annotations: [
{
type: "line",
mode: "horizontal",
scaleID: "x",
value: 1,
borderColor: "white",
borderWidth: 2,
},
],
},
}

How to display Range Apex chart when we have [start, end] are same at some time?

//Here #y:[start,end] at some point i have same start and end value but currently apex range chart don't show range bar when [start,end] is same value, but i need to show the bar for same [start,end] also how to do this?
var options = {
series: [
{
name: 'Bob',
data: [
{
x: 'Design',
y: [
4,4
]
},
{
x: 'Code',
y: [
5,7
]
},
{
x: 'Code',
y: [
0,1
]
},
{
x: 'Test',
y: [
10,10
]
},
{
x: 'Test',
y: [
4,4
]
},
{
x: 'Validation',
y: [
2,2
]
},
{
x: 'Design',
y: [
1,2
]
}
]
},
{
name: 'Joe',
data: [
{
x: 'Design',
y: [
1,2
]
},
{
x: 'Test',
y: [
6,6
]
},
{
x: 'Code',
y: [
9,9
]
},
{
x: 'Deployment',
y: [
5,5
]
},
{
x: 'Design',
y: [
4,7
]
}
]
},
{
name: 'Dan',
data: [
{
x: 'Code',
y: [
3,5
]
},
{
x: 'Validation',
y: [
3,3
]
},
]
}
],
chart: {
height: 450,
type: 'rangeBar'
},
plotOptions: {
bar: {
horizontal: true,
barHeight: '80%'
}
},
xaxis: {
min: 0,
max: 10
},
stroke: {
width: 1
},
fill: {
type: 'solid',
opacity: 0.6
},
legend: {
position: 'top',
horizontalAlign: 'left'
}
//i need to show the bar for same [start,end] also how to do this?
//Please help me in this.
For values ​​that have the same range, that is, the same start and end, you can add attributes to control the width and height of the bar, as well as the color, you also have to specify the value:
goals: [
{
value: 3,
// strokeHeight: 10,
strokeWidth: 3,
strokeColor: "#FEB019"
}
]
Example codesandbox
Useful apexcharts links:
https://apexcharts.com/react-chart-demos/column-charts/column-with-markers/
https://apexcharts.com/docs/chart-types/range-bar-chart/

chartjs: bars smaller than actual column, tooltip doesn't display

As you can see my bars are not covering the entire width of the label 'column'.
My tooltip only shows if I am exactly hovering the bar, or, if I remove the bars, exactly on the line point.
options: {
plugins: {
legend: { display: false },
title: { display: false },
tooltip: {
displayColors: false, backgroundColor: '#ffffff',
bodyColor: '#595f69', bodyFont: {size: 14},
borderColor: '#595f69', borderWidth: 1,
titleFont: {size: 0}
}
},
responsive: true, aspectRatio: 4,
scales: {
y: { display: true, suggestedMin: 0, suggestedMax: 80, ticks: { stepSize: 20 } },
y1: {display: false, suggestedMin: 0, suggestedMax: 80, ticks: { stepSize: 2 }},
x: { grid: { drawBorder: false, display: false } }
I tried plugins like chartjs crosshair, but don't manage to make it work with typescript.
How can I make it so that anywhere my mouse hover in the label 'column' area, the tooltip displays?
You can set the intersect property to false to always get the tooltip without needing to intersect the bar exactly:
var options = {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderWidth: 1
}]
},
options: {
plugins: {
tooltip: {
intersect: 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>
You can make your own tooltip by editing the callbacks, i had to get the nearest values around my cursor, from all datasets, on my line chart. this works for me on Chartjs 2.9.3:
tooltips: {
mode: "x",
position: "nearest",
intersect: false,
callbacks: {
beforeBody: function(tooltipItems, allData) {
let x = tooltipItems[0].x; // get x coordinate
let datasets = allData.datasets; // datasets
let values = [];
for (i in datasets) {
let dataset = datasets[i];
let meta = this._chart.getDatasetMeta(i); // dataset metadata
let xScale = this._chart.scales[meta.xAxisID]; // dataset's x axis
let xValue = xScale.getValueForPixel(x); // we get the x value on the x axis with x coordinate
let data = dataset.data // data
// search data for the first value with a bigger x value
let index = data.findIndex(function(o) {
return o.x >= xValue;
});
let value = data[index]; // this is our nearest value
// format label
if (isNaN(value.ymax)) {
values.push(`${dataset.label}: ${value.y}\n`);
} else {
values.push(`${dataset.label}: ${value.y}, min: ${value.ymin}, max: ${value.ymax}\n`)
}
}
return values.join(""); // return label
},
label: function() { // this needs to be empty
},
}
},

chartjs doesn't render dates properly

I made a custom chartjs component in reactjs and want to render dates in xAxes and numbers from -1 to 1 in yAxes but it renders data not in a proper way.
import React, { useRef, useEffect } from "react";
import Chart from "chart.js";
const ChartComponent = ({ data, label, min, max }) => {
const canvasRef = useRef(null);
useEffect(() => {
const canvasObj = canvasRef.current;
const context = canvasObj.getContext("2d");
new Chart(context, {
type: "line",
data: {
datasets: [
{
label: label,
backgroundColor: "transparent",
data: data,
},
],
},
options: {
scales: {
xAxes: [
{
type: "time",
distribution: "linear",
time: {
unit: "month",
displayFormats: {
quarter: "YYYY mm dd",
},
},
},
],
yAxes: [
{
ticks: {
suggestedMax: max,
suggestedMin: min,
},
},
],
},
},
});
}, [data, label, min, max]);
return <canvas ref={canvasRef}> </canvas>;
};
export default ChartComponent;
and I'm passing the data like this to the component
<ChartComponent
min={-1}
max={1}
label="date"
data={[
{
x: "30/03/2018",
y: 0.1158,
},
{
x: "24/09/2018",
y: 0.1975,
},
{
x: "23/12/2018",
y: 0.1913,
},
{
x: "23/03/2019",
y: 0.2137,
},
]}
/>;
I have to metion that I have done the same thing and that is working alright this is example below
<ChartComponent
min={1270}
max={1272}
label=" مساحت دریاچه"
data={[
{
x: "04/02/2017",
y: 1270.7,
},
{
x: "06/26/2017",
y: 1270.74,
},
{
x: "09/19/2017",
y: 1270.31,
},
{
x: "12/18/2017",
y: 1270.28,
},
{
x: "06/16/2018",
y: 1270.81,
},
{
x: "09/24/2018",
y: 1270.27,
},
{
x: "12/23/2018",
y: 1270.54,
},
{
x: "05/25/2019",
y: 1271.94,
},
{
x: "06/18/2019",
y: 1271.84,
},
{
x: "09/19/2019",
y: 1271.31,
},
{
x: "12/18/2019",
y: 1271.25,
},
{
x: "03/12/2020",
y: 1271.48,
},
{
x: "06/25/2020",
y: 1271.72,
},
]}
/>;
any recommendation would be appreciated. thank you.
The problem is that the date strings you provide are not of ISO 08601 nor RFC 2822 Date time format, hence they cannot be parsed by Moment.js, which is internally used by Chart.js.
To make it work, you have to define xAxes.time.parser: "DD.MM.YYYY".
Please take a look at below runnable code and see how it works. This is pure JavaScript example but it should also work with react-chartjs-2.
new Chart("myChart", {
type: "line",
data: {
datasets: [{
label: 'My Dataset',
data: [
{ x: "30/03/2018", y: 0.1158 },
{ x: "24/09/2018", y: -0.1975 },
{ x: "23/12/2018", y: 0.1913 },
{ x: "23/03/2019", y: -0.2137 }
],
fill: false
}]
},
options: {
scales: {
xAxes: [{
type: "time",
time: {
parser: "DD.MM.YYYY",
unit: "month",
displayFormats: {
month: "YYYY MM DD",
}
}
}],
yAxes: [{
ticks: {
suggestedMax: 1,
suggestedMin: -1
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.bundle.min.js"></script>
<canvas id="myChart" height="100"></canvas>
As I already mentioned, Chart.js internally uses Moment.js for the functionality of the time axis. Therefore make sure to use the bundled version of Chart.js that includes Moment.js in a single file.

How to set X coordinate for each bar with react chart js 2?

I want to make a chart with min and max vertical lines and bars between them. I can't find information how to set bars' X coordinate or make custom line plot with vertical 'bars' instead of points.
And also I don't understand how to scale X axis, why MAX is left-side MIN? Min=22.5, Max=24.5
let plot_options = {
showScale: true,
pointDot: true,
showLines: true,
maintainAspectRatio: false,
annotation: {
annotations: [
{
type: 'line',
mode: 'vertical',
scaleID: 'y-axis-0',
value: min,
borderColor: 'red',
borderWidth: 2,
label: {
backgroundColor: 'red',
content: 'Min',
enabled: true,
},
},
{
type: 'line',
mode: 'vertical',
scaleID: 'y-axis-0',
value: max,
borderColor: 'red',
borderWidth: 2,
label: {
backgroundColor: 'red',
content: 'MAX',
enabled: true,
},
},
]
},
title: {
display: true,
text: plotHeader,
},
responsive: true,
legend: {
display: false,
},
scales: {
xAxes: [{
scaleLabel: {
display: true,
labelString: labelx
},
ticks: {
min: min,
max: max
}
}],
yAxes: [{
scaleLabel: {
display: true,
labelString: labely
},
ticks: {
beginAtZero: true,
},
}]
},
}
data = {
barPercentage: 0.5,
barThickness: 6,
maxBarThickness: 8,
minBarLength: 2,
labels: labels,
datasets: [{
data: values,
borderColor: BLUE,
backgroundColor: BLUE
}]
}
<Bar options={plot_options} data={data} plugins={ChartAnnotation} />
That's what I expect:
This solution is based on this answer for the positioning of the bars on a linear x-axis.
You can further use the Plugin Core API to draw the vertical min and max lines with their labels directly on the canvas. The API offers a number of hooks that can be used to perform custom code. In your case, you could use the afterDraw hook together with CanvasRenderingContext2D.
Please take a look at the runnable code below and see how it works. It should not be too hard to make similar code work with react-chartjs-2.
new Chart("chart", {
type: 'bar',
plugins: [{
afterDraw: chart => {
let ctx = chart.chart.ctx;
ctx.save();
let xAxis = chart.scales['x-axis-0'];
let yAxis = chart.scales['y-axis-0'];
let dataset = chart.data.datasets[0];
[dataset.min, dataset.max].forEach((v, i) => {
var x = xAxis.getPixelForValue(+v * 1000);
ctx.fillStyle = 'red';
ctx.font = '14px Arial';
ctx.textAlign = 'center';
ctx.fillText(i == 0 ? 'Min' : 'Max', x, yAxis.top + 14);
ctx.fillStyle = 'gray';
ctx.font = '12px Arial';
ctx.fillText(v, x, yAxis.bottom + 20);
ctx.beginPath();
ctx.moveTo(x, yAxis.top + 20);
ctx.strokeStyle = 'red';
ctx.lineTo(x, yAxis.bottom + 3);
ctx.stroke();
});
ctx.restore();
}
}],
data: {
datasets: [{
min: 22.5,
max: 24.5,
data: [
{ x: '22.83', y: 18 },
{ x: '23.17', y: 15 },
{ x: '23.44', y: 13 },
{ x: '24.32', y: 20 }
],
borderColor: 'blue',
backgroundColor: 'blue',
barThickness: 20
}]
},
options: {
legend: {
display: false,
},
scales: {
xAxes: [{
offset: true,
type: 'time',
time: {
parser: 'X',
unit: 'millisecond',
displayFormats: {
millisecond: 'X'
}
},
ticks: {
source: 'data',
min: '22.5',
callback: (v, i, values) => values[i].value / 1000
},
gridLines: {
display: false
},
}],
yAxes: [{
ticks: {
beginAtZero: true,
max: 22,
stepSize: 2
}
}]
}
}
});
canvas {
max-width: 500px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.bundle.min.js"></script>
<canvas id="chart" height="200"></canvas>

Resources