I'm trying to make the below graph using chart js in React 18:
So far I've written the below code and tried to limit the x and y axes through maxTicksLimit, but I suppose I'm missing something here:
import "./styles.css";
import { data } from "./data";
import { Line } from "react-chartjs-2";
import moment from "moment";
export default function App() {
const series = data.cpu.values.map((item) => item[1]);
const labels = data.cpu.values.map((item) =>
moment(item[0] * 1000).format("hh:mm:ss")
);
const options = {
responsive: true
};
const datax = {
labels,
datasets: [
{
label: "CPU USAGE",
data: series,
borderColor: "rgb(255, 99, 132)",
backgroundColor: "rgba(255, 99, 132, 0.5)",
pointRadius: 0,
fill: true
}
],
scales: {
xAxes: [
{
ticks: {
maxTicksLimit: 9
}
}
],
yAxes: [
{
ticks: {
maxTicksLimit: 4
}
}
]
}
};
return (
<div className="App">
<Line options={options} data={datax} />
</div>
);
}
I get the below output:
I would appreciate any help CodeSandBox
To solve your problem, define options as follows.
const options = {
responsive: true,
scales: {
x: {
ticks: {
maxTicksLimit: 9
}
},
y: {
ticks: {
maxTicksLimit: 4
}
}
}
};
For further information, consult Tick Configuration Options from the Chart.js documentation.
Please take a look at your amended CodeSandbox and see how it works.
Related
import React from "react";
import { Line } from "react-chartjs-2";
// "chart.js": "^2.9.4",
// "react-chartjs-2": "^2.11.1"
const ext_data = [11, 19, 3, 5, 2, 3, 14, 19];
const ll = Array.from(Array(ext_data.length).keys());
const data = {
labels: ll,
datasets: [
{
label: "Profit$",
data: ext_data,
fill: false,
backgroundColor: "rgb(255, 99, 132)",
borderColor: "rgba(255, 99, 132, 0.4)"
}
]
};
const options = {
scales: {
yAxes: [
{
ticks: {
beginAtZero: true
}
}
]
}
};
const LineChart = () => (
<>
<div className="header">
<h1 className="title">Profit Trend</h1>
<div className="links"></div>
</div>
<Line data={data} options={options} />
</>
);
export default LineChart;
I am trying to add x-axis name : "time" and y-axis name: "number of cars".
I went into the documentation : https://www.chartjs.org/docs/latest/axes/labelling.html
However, I was not able to find something that was useful.
Thank you for your time.
In react-chartjs-2, to add your title to your axis, just add this to your yAxes array of options (options.scales.yAxes[]):
scaleLabel: {
display: true,
labelString: "number of cars",
fontColor: "color you want",
}
same for your xAxes.
I am trying to do up a custom y-axis to convert 1 to a custom string. E.g. 1 is "Apple"
Been trying different solutions and none seems to work for the "scales" option. I doing its on react typescript.
Also, I am very confused about whether to use [], "y", "yAxis" or "yAxes".
const opt = {
plugins: {
legend: {
display: false,
labels: {
color: 'rgb(255, 99, 132)'
}
},
scales: {
yAxes: [{
ticks: {
beginAtZero: false,
min: 0,
stepSize: 2,
callback: function(value : any) {
return `${value}`
}
}
}]
}
}
}
return (
<div>
<Bar
data={state}
options={opt}
/>
</div>
)
Example of the current problem
I'm using react-chartjs-2 v4.1 with ChartJS v3.8 in typescript.
I'd like to draw a horizontal line through my bar graph as shown below:
I find many half-written examples of which I cannot create a functional one. I couldn't find any complete, working example on how to use annotations.
My Code
I've added the chartjs-plugin-annotation package to my project.
Below is the code for a react component showing the graph of the screenshot. The annotation, however, does not work.
Can anyone tell me what's wrong with the code?
import React from 'react';
import { Bar } from 'react-chartjs-2';
export const MyChart: React.FC = () => {
const options2 = {
plugins: {
legend: {
display: false,
},
annotation: {
annotations: [
{
id: 'a-line-1',
type: 'line',
mode: 'horizontal',
scaleID: 'y',
value: 1.0,
borderColor: 'red',
borderWidth: 4,
label: {
enabled: false,
content: 'Test label',
},
},
],
},
},
};
const data2 = {
labels: [ 'a', 'b'],
datasets: [ { data: [1, 2] } ],
};
return (<Bar options={options2} data={data2} height={150} />
);
};
You dont import and register the annotation plugin:
import { Chart } from 'chart.js';
import annotationPlugin from 'chartjs-plugin-annotation';
Chart.register(annotationPlugin);
Based on LeeLenalee's answer here's a fully working example.
Changes to code in question:
import and register annotationPlugin
set annotation type to type: 'line' as const (not just type: 'line'). Otherwise typescript complains.
import React from 'react';
import { Bar } from 'react-chartjs-2';
import { Chart } from 'chart.js';
import annotationPlugin from 'chartjs-plugin-annotation';
Chart.register(annotationPlugin);
export const MyChart: React.FC = () => {
const options2 = {
plugins: {
legend: {
display: false,
},
annotation: {
annotations: [
{
id: 'a-line-1',
type: 'line' as const, // important, otherwise typescript complains
mode: 'horizontal',
scaleID: 'y',
value: 1.0,
borderColor: 'red',
borderWidth: 4,
label: {
enabled: false,
content: 'Test label',
},
},
],
},
},
};
const data2 = {
labels: [ 'a', 'b'],
datasets: [ { data: [1, 2] } ],
};
return (<Bar options={options2} data={data2} height={150} />
);
};
Screen Ratio 100%
enter image description here
Screen Ratio 70%
enter image description here
const chartData = {
type: 'area',
height: 95,
options: {
chart: {
id: 'rental-Chart',
sparkline: {
enabled: true,
},
},
dataLabels: {
enabled: false,
},
stroke: {
curve: 'smooth',
width: 1.3,
},
tooltip: {
fixed: {
enabled: false,
},
x: {
show: true,
},
y: {
title: 'Ticket ',
},
marker: {
show: false,
},
},
},
series: [
{
name: 'Number of Rentals : ',
data: [0, 5, 3, 15, 20, 10, 22],
},
],
};
export default chartData;
import React, { useEffect, useState } from 'react';
import { Card, Grid, Typography } from '#mui/material';
import ApexCharts from 'apexcharts';
import Chart from 'react-apexcharts';
import chartData from './Product-Stock-Chart';
function BajajAreaChartCard() {
useEffect(() => {
const newSupportChart = {
...chartData.options,
chart: {
width: '100%',
},
};
ApexCharts.exec(`rental-Chart`, 'updateOptions', newSupportChart, true);
}, []);
return (
<Chart {...chartData} />
);
}
export default BajajAreaChartCard;
It works normally when it is the default size, but if reduce the size, the size of the chart changes as shown in the picture.
I don`t know what to do to solve this problem..
please help me..
I'm trying to implement a line graph through chart js on react, however, whenever my function sets the x and y axis data, it keeps returning a line chart that is vertical with x-axis values at 0.
Here is my code below:
import React, { useEffect, useState } from 'react'
import './LineGraph.css'
import {Line} from "react-chartjs-2"
function LineGraph() {
const [ graphData, setGraphData ] = useState([])
const data = [{x:10, y:20}, {x:15, y:10}, {x:12, y:4}]
const createMockData = () => {
let data = [];
let value = 50;
for(var i = 1; i < 366; i++) {
let date = new Date()
date.setHours(0,0,0,0)
date.setDate(i)
value += Math.round((Math.random() < 0.5 ? 1 : 0) * Math.random() * 10)
data.push({x: value, y:value})
console.log(data)
}
setGraphData(data)
}
useEffect(()=> {
createMockData()
}, [])
return (
<div className="linegraph">
<Line
data={{
datasets: [
{
type: "line",
data: graphData,
backgroundColor: "black",
borderColor: "#5AC53B",
borderWidth: 2,
pointBorderColor: 'rgba(22, 22, 22, 0)',
pointBackgroundColor: 'rgba(0,0,0,0)',
pointHoverBackgroundColor: '#5AC53B',
pointHoverBorderColor: '#000000',
pointHoverBorderWidth: 4,
pointHoverRadius: 6,
}
]
}}
options={{
plugins:{
legend: {
display: false
},
tooltips: {
interaction: {
mode: "index",
intersect: false
}
}
},
scales: {
x: [
{
type: "time",
time: {
format: "MM/DD/YY",
tooltipFormat: "ll",
},
ticks: {
display: false,
}
},
],
y: {
ticks: {
display: false
}
}
}
}}
/>
</div>
)
}
export default LineGraph
I'm using react-charts-2, latest version 3.5.1. I think the main problem is with my x-axis because my y-coordinates all show up, which is why the line is vertical, however, all the x values are 0, so their is not diagonal or correlated uphill/downhill line. Please help me resolve this
You are defining the x axis scale as an array , this is v2 syntax. All scales have to be defined as an object. So at the moment chart.js sees your scale as a category scale instead of a time scale and it cant handle number inputs as labels.
To fix this you will need to change your scale like so:
scales: {
x: {
type: "time",
time: {
format: "MM/DD/YY",
tooltipFormat: "ll",
},
ticks: {
display: false,
}
},
,
}
For using the timescale you will also need a date adapter, since you are using js dates you can just use the normal datefns adapter like so:
npm install date-fns chartjs-adapter-date-fns --save
import {Line} from "react-chartjs-2"
import 'chartjs-adapter-date-fns';