React + ChartJS V3: Annoations don't work - reactjs

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} />
);
};

Related

Make part of datalabels bold in ChartJS

I use chartjs for the charts and chartjs-plugin-databels for the data labels within each bar.
I need make value of line bold and leave the first part unchanged.
I try find solution in documentaion:
https://chartjs-plugin-datalabels.netlify.app/guide/labels.html#multiple-labels and https://www.chartjs.org/docs/latest/charts/bar.html, but there is not result.
Pictures:
It must look.
vs
It looks.
My code
import _ from "lodash";
import { Bar } from "react-chartjs-2";
import ChartDataLabels from "chartjs-plugin-datalabels";
const options = {
indexAxis: "y" as const,
responsive: true,
elements: {
bar: {
borderWidth: 1,
},
},
scales: {
y: {
ticks: {
display: false,
},
grid: {
display: false,
},
},
x: {
grid: {
borderDash: [10, 10],
},
},
},
plugins: {
datalabels: {
anchor: `start` as "start", import _ from "lodash";
align: `end` as "end", import _ from "lodash";
formatter: function (value: any, context: any) {
return (
context.chart.data.labels[context.dataIndex] +
": " +
context.dataset.data[context.dataIndex]
);
},
},
legend: {
display: false,
},
title: {
display: false,
},
},
};
const labels = [
"Some label 1",
"Some label 1",
"Some label 1",
"Some label 1",
"Some label 1",
"Other",
];
const data = {
labels,
datasets: [
{
data: labels.map(() => Math.floor(Math.random() * 10000)), // random values
maxBarThickness: 28,
inflateAmount: 3,
},
],
};
const HorizontalBarChart = () => {
return (
<Bar options={options} data={data} plugins={[ChartDataLabels]} />
);
};
What information to add to make the question clearer?

How do we solve the width change problem caused by resizing in apexchart?

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..

Next.js problem with #ant-design/charts, error

I work on a large project (monorepo). The technology stack is Next, Apollo GraphQL, Ant-Design. I wanted to add the #ant-design/charts package, but it crashes the error below. I have run out of ideas for repair: c
Error on page:
../../node_modules/#antv/xflow/dist/index.css
Global CSS cannot be imported from within node_modules.
Read more: https://nextjs.org/docs/messages/css-npm
Location: ../../node_modules/#ant-design/flowchart/es/graph/index.js
Terminal:
(node:40023) [DEP_WEBPACK_MODULE_ISSUER] DeprecationWarning: Module.issuer: Use new ModuleGraph API
(Use `node --trace-deprecation ...` to show where the warning was created)
error - ../../node_modules/#antv/xflow/dist/index.css
Global CSS cannot be imported from within node_modules.
Read more: https://nextjs.org/docs/messages/css-npm
Use dynamic import of Next.js and false server side rendering for this module.
import dynamic from 'next/dynamic';
const Line = dynamic(() => import('#ant-design/charts').then(({ Line }) => Line),
{ ssr: false }
);
const data = [
{
year: '1991',
value: 3,
},
{
year: '1992',
value: 4,
}
]
const LineChart = () => {
const config = {
data: data,
xField: 'year',
yField: 'value',
label: {},
point: {
size: 5,
shape: 'diamond',
style: {
fill: 'white',
stroke: '#5B8FF9',
lineWidth: 2,
},
},
tooltip: { showMarkers: true },
state: {
active: {
style: {
shadowBlur: 4,
stroke: '#000',
fill: 'red',
},
},
},
interactions: [{ type: 'marker-active' }],
slider: {
start: 0.1,
end: 0.8,
},
};
return (
<div>
<Line {...config} />
</div>
);
};
export default LineChart;
Closed, installing sub package #ant-design/plots solved my problem

make every labels different in doughnut chart (react js)

i have double doughnut chart in my react js project code. in that double chart dougnut i want to have 3 different labels in 3 different colour, what should i write to make that?
this my code now
var dataDoughnut1 = {
labels: ["Blue", "Green", "Red"],
datasets: [{
data: [1000],
backgroundColor: [
"#36A2EB"
],
labels: [
'Blue',
]
}, {
data: [400,600],
backgroundColor: [
"#C4D34C",
"#F7464A"
],
labels: [
'Green',
'Red'
],
}],
};
until now with that code the output labels is "blue","green" and "green" again
i want to make 3 different labels in 3 different colour too, anyone can help me?
result :
Ok, so i have read the docs of react-chartjs-2 and their Doughnut Chart does not support rendering two datasets like you want, i came up with this workaround that will help you to achieve what you want.
import React from "react";
import { Doughnut } from "react-chartjs-2";
import { MDBContainer } from "mdbreact";
const App = () => {
var dataDoughnut1 = {
labels: ["Blue", "Green", "Red"],
datasets: [
{
data: [1000, 0, 0],
//You should set here all the other colors desired from the other datasets so it can be interpreted by the component
backgroundColor: ["#36A2EB"],
labels: ["Blue"],
},
{
data: [400, 600],
backgroundColor: ["#C4D34C", "#F7464A"],
labels: ["Green", "Red"],
},
],
};
const options = {
responsive: true,
legend: {
display: false,
},
tooltips: {
callbacks: {
label: function (tooltipItem, data) {
console.log(tooltipItem.datasetIndex);
var dataset = data.datasets[tooltipItem.datasetIndex];
var index = tooltipItem.index;
return dataset.labels[index] + ": " + dataset.data[index];
},
},
},
};
return (
<MDBContainer>
<h3 className="mt-5">Doughnut chart</h3>
<Doughnut data={dataDoughnut1} options={options} />
</MDBContainer>
);
};
export default App;
Here is the result

Unable to convert timestamp to hours minutes and secondes in React apex-chart

I am using react apex chart to create a chart that will display the average response time for each agent.
I have managed to get the result in a timestamp format but i am unable to convert that into hours, minutes and seconds to display that in yaxis, i have checked the documentation docs link but they are giving examples for date time only.
here is the result that i am getting with the component bellow
import React, { useState } from 'react';
import Chart from 'react-apexcharts';
const AvgResponseTimeChart = (props) => {
const { prod_data } = props;
const [ data, setData ] = useState([
{
x: 'Agent one',
y: 1589670005
},
{
x: 'Agent one',
y: 1589670307
}
]);
const [ series, setSeries ] = useState([ { data } ]);
const [ options, setOptions ] = useState({
chart: {
type: 'bar',
height: 350
},
plotOptions: {
bar: {
horizontal: false,
columnWidth: '25%',
endingShape: 'rounded'
}
},
dataLabels: {
enabled: false
},
stroke: {
show: true,
width: 2,
colors: [ 'transparent' ]
},
xaxis: {
type: 'category'
},
yaxis: {
labels: {
datetimeFormatter: {
formatter: function(value, timestamp) {
return new Date(timestamp).toLocaleTimeString();
}
}
}
},
fill: {
opacity: 1
},
tooltip: {
y: {
formatter: function(value, timestamp) {
return new Date(timestamp);
}
}
}
});
return (
<div id="chart">
<Chart options={options} series={series} type="bar" height={350} />
</div>
);
};
export default AvgResponseTimeChart;
I have searched for similar issues without success if, someone can help me with that i will be really grateful
Try to add lables to yaxis in chartOptions this way:
labels: {
show: true,
formatter: (val) => { return new Date(val); }
}
And remove the tooltip as well.

Resources