Chart line not appearing in a semi log chart using chart.js - javascript

I am using react-chartjs-2 to create a semi log chart using some simple data.
I tried many examples but in the final chart the line isn't drawn nor I see any error in the browser console.
I am using Next.js & Tailwind CSS for this project.
I also tried using the techniques described in the time series charts but those also don't work
I have figured out how to create the axis and ticks , now how do I draw the line ?
Here is my code.
index.js
import {
Chart as ChartJS,
CategoryScale,
LogarithmicScale,
LogarithmicScaleOptions,
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend,
} from "chart.js";
import { Line } from "react-chartjs-2";
ChartJS.register(
LogarithmicScale,
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend
);
export const options = {
scales: {
x: {
display: true,
type: "logarithmic",
min: 0.000001,
max: 1,
},
y: {
display: true,
min: 400,
max: 2500,
},
},
responsive: true,
plugins: {
legend: {
position: "top",
},
title: {
display: true,
text: "5W-10R",
},
},
};
const vmax = [2000, 1750, 1500, 1250, 1000, 750, 500];
const tm = [
0.0000125, 0.00001633, 0.00002222, 0.000032, 0.00005, 0.0002, 0.0008,
];
export const data = {
tm,
datasets: [
{
label: "Dataset 1",
data: vmax,
borderColor: "rgb(255, 99, 132)",
backgroundColor: "rgba(255, 99, 132, 0.5)",
},
],
};
export default function Home({}) {
return (
<div className="">
<div className="flex flex-col items-center justify-center min-h-screen py-2">
<main className="flex flex-col items-center w-full flex-1 px-10 ">
<Line options={options} data={data} />
</main>
</div>
</div>
);
}
Result:

You don't pass an option to the labels array, you pass the tm variable which means it will use that as a key, you need to pass it as:
const data = {
labels: tm,
datasets: []
}

Related

How to limit chart js to display existing axis values?

The bounty expires in 6 days. Answers to this question are eligible for a +100 reputation bounty.
nika wants to draw more attention to this question.
I'm adding Chart js to my React project where I need to display data per day, everything seems to be working fine, except when I add pan functionality, the chart scrolls left/right and adds some random dates.
for example this is the data I want to display:
data: [
{ x: "2021-01-01", y: 10 },
{ x: "2021-01-02", y: 20 },
{ x: "2021-01-03", y: 20 },
{ x: "2021-01-04", y: 20 },
{ x: "2021-01-05", y: 20 }
]
this is how chart looks if I scroll left
I don't understand where Dec 31 is coming from, also if I scroll to the right, I'm getting additional days that are not defined in the data( January 6, 7 etc). How can I restrict the pan to scroll according to the provided date range only? ( don't pan to Dec 31 or January 6)
My code in codesandbox
My code:
import "./styles.css";
import { Bar } from "react-chartjs-2";
import {
Chart as ChartJS,
CategoryScale,
Title,
LinearScale,
PointElement,
Tooltip,
Legend,
TimeScale,
BarElement
} from "chart.js";
import "chartjs-adapter-date-fns";
import { enUS } from "date-fns/locale";
ChartJS.register(
BarElement,
CategoryScale,
LinearScale,
Title,
Tooltip,
Legend,
zoomPlugin,
TimeScale
);
import zoomPlugin from "chartjs-plugin-zoom";
import { useRef } from "react";
export default function App() {
const options = {
maintainAspectRatio: false,
responsive: true,
elements: {
point: {
radius: 0
},
line: {
borderWidth: 1.5
}
},
scales: {
x: {
type: "time",
time: {
unit: "day"
},
ticks: {
color: "rgba( 0, 0, 1)"
},
grid: {
color: "rgba(0, 0, 0, 1)"
}
},
y: {
ticks: {
color: "rgba(0, 0, 0, 1)"
},
grid: {
color: "rgba(0, 0, 0, 1)"
}
}
},
plugins: {
zoom: {
pan: {
enabled: true,
mode: "x",
speed: 10
}
}
}
};
const data = {
datasets: [
{
data: [
{ x: "2021-01-01", y: 10 },
{ x: "2021-01-02", y: 20 },
{ x: "2021-01-03", y: 20 },
{ x: "2021-01-04", y: 20 },
{ x: "2021-01-05", y: 20 }
]
}
]
};
const canvasRef = useRef();
return (
<div className="App">
<Bar
ref={canvasRef}
options={options}
data={data}
height={null}
width={null}
/>
</div>
);
}
I hope you are doing good.
The Dec 31 date is added to the chart because the x-axis time scale is starting from December 31, 2020 by default, which is the beginning of the week that includes January 1, 2021. The additional days (e.g., January 6, 7, etc.) that appear when you pan to the right are added because the chart is using the zoom plugin, which allows the user to pan beyond the range of the data.
To restrict the pan to scroll according to the provided date range only, you can set the min and max values of the x-axis time scale.
The fixed code :
import "./styles.css";
import { Bar } from "react-chartjs-2";
import {
Chart as ChartJS,
CategoryScale,
Title,
LinearScale,
PointElement,
Tooltip,
Legend,
TimeScale,
BarElement
} from "chart.js";
import "chartjs-adapter-date-fns";
import { enUS } from "date-fns/locale";
ChartJS.register(
BarElement,
CategoryScale,
LinearScale,
Title,
Tooltip,
Legend,
zoomPlugin,
TimeScale
);
import zoomPlugin from "chartjs-plugin-zoom";
import { useRef } from "react";
export default function App() {
const startDate = new Date("2021-01-01");
const endDate = new Date("2021-01-05");
const options = {
maintainAspectRatio: false,
responsive: true,
elements: {
point: {
radius: 0
},
line: {
borderWidth: 1.5
}
},
scales: {
x: {
type: "time",
time: {
unit: "day"
},
ticks: {
color: "rgba(0, 0, 1)"
},
grid: {
color: "rgba(0, 0, 0, 1)"
},
min: startDate,
max: endDate
},
y: {
ticks: {
color: "rgba(0, 0, 0, 1)"
},
grid: {
color: "rgba(0, 0, 0, 1)"
}
}
},
plugins: {
zoom: {
pan: {
enabled: true,
mode: "x",
speed: 10,
limits: {
x: { min: startDate, max: endDate }
}
}
}
}
};
const data = {
datasets: [
{
data: [
{ x: "2021-01-01", y: 10 },
{ x: "2021-01-02", y: 20 },
{ x: "2021-01-03", y: 20 },
{ x: "2021-01-04", y: 20 },
{ x: "2021-01-05", y: 20 }
]
}
]
};
const canvasRef = useRef();
return (
<div className="App">
<Bar
ref={canvasRef}
options={options}
data={data}
height={null}
width={null}
/>
</div>
);
}
I've added startDate and endDate variables which define the range of the chart, and set the minimum and maximum values for the x-axis to these variables. Additionally, I added a limits option to the zoom.pan configuration to restrict panning to the defined date range.
Hopefully It will help you.
Kind regards.

Add a gradient background to react-chartjs-2

I am currently trying to add a gradient background with a slight transparency to a radar graph inside a react component. I have only been able to find solutions for this problem by referencing a chartjs canvas within an html file, but no solutions via a react component in a tsx/jsx file.
Desired Result I am looking for, and the
Current Result
The code below is used to achieve the current result.
import { Chart } from 'react-chartjs-2';
import { Chart as ChartJS, LineController, LineElement, PointElement, LinearScale, Title, Filler, RadialLinearScale } from 'chart.js';
ChartJS.register(LineController, RadialLinearScale, LineElement, PointElement, LinearScale, Filler, Title);
const labels = ['Thing 1', 'Thing 2', 'Thing 3', 'Thing 4', 'Thing 5', 'Thing 6'];
const chartData = [5, 3, 4, 5, 2, 4];
const data = {
labels: labels,
datasets: [
{
data: chartData,
fill: true,
backgroundColor: 'pink',
borderColor: 'transparent',
pointBorderColor: 'transparent',
pointBackgroundColor: 'transparent',
},
],
};
const options = {
scales: {
r: {
grid: {
lineWidth: 2,
},
angleLines: {
lineWidth: 2,
},
gridLines: {
display: false
},
ticks: {
display: false,
maxTicksLimit: 1
},
}
}
}
const RadarGraph = () => {
return (
<Chart type="radar" data={data} options={options}/>
)
}
export default RadarGraph;
You will need to use a scriptable function for the backgroundColor which contains the chart which contains the context like so:
const data = {
labels: labels,
datasets: [
{
data: chartData,
fill: true,
backgroundColor: ({chart: {ctx}}) => {
const bg = ctx.createLinearGradient(paramters);
// More config for your gradient
return bg;
}
},
],
};

Error in fill Gradient Color in Line Chart.js

I try to Fill gradient Color in my Line chart but there was some error restricted me from using canvas.
In Code Below there are 3 function: Options contain options of the line chart, Data contain data(i have error in this function), LineChart call and return line chart
import React from "react";
import {
Chart as ChartJS,
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend,
Filler
} from "chart.js";
import { Line } from "react-chartjs-2";
ChartJS.register(
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend,
Filler
);
export const options = {
responsive: true,
maintainAspectRatio: true,
aspectRatio: 1,
plugins: {
legend: {
position: "top",
display: false,
},
title: {
display: true,
text: "Calories Friend Ranking",
},
},
backgroundColor: "#fff",
borderColor: "#fff",
};
export const data = (canvas) => {
const ctx = canvas.getContext("2d");
const gradient = ctx.createLinearGradient(0, 0, 0, 400);
gradient.addColorStop(0, 'rgba(250, 61, 0 ,1)');
gradient.addColorStop(1, 'rgba(250, 61, 0 ,0)');
return {
labels: ["0","cuong","hien"],
datasets: [
{
backgroundColor : gradient,
borderColor : "rgba(250, 61, 0, 1)",
tension: 0.4,
fill: 'start',
data : [0,500,2000]
}
]
}
}
export default function LineChart(props) {
let { RankData } = props;
var NameLabels = ["0"]
var CaloriesDatas = [0]
for (var i = RankData.length - 1; i >= 0; i--) {
NameLabels.push(RankData[i].displayName)
CaloriesDatas.push(RankData[i].carloriesBurned)
}
//error in data function :"Property 'datasets' is missing in type '(canvas: any) =>.."
return (<Line data={data} options={options} />);
}
I have error in function Data "Here is the error that i met"

Styling background (fill) with ChartJs and React [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 12 months ago.
Improve this question
I want to create a Line chart, styled as an Area Chart, in React by using the chartJS library ('react-chartjs-2')
This is what I want to achieve, like background (fill) with some opacity below the line:
Code:
import React from 'react';
import {
Chart as ChartJS,
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend,
} from 'chart.js';
import { Line } from 'react-chartjs-2';
import faker from 'faker';
ChartJS.register(
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend
);
export const options = {
responsive: true,
plugins: {
legend: {
position: 'top' as const,
},
title: {
display: true,
text: 'Chart.js Line Chart',
},
},
};
const labels = ['January', 'February', 'March', 'April', 'May', 'June', 'July'];
export const data = {
labels,
datasets: [
{
label: 'Dataset 1',
data: labels.map(() => faker.datatype.number({ min: -1000, max: 1000 })),
borderColor: 'rgb(255, 99, 132)',
backgroundColor: '#000000',
fill: {
target: 'origin',
above: 'rgb(255, 0, 0)', // Area will be red above the origin
below: '#000000' // And blue below the origin
}
},
{
label: 'Dataset 2',
data: labels.map(() => faker.datatype.number({ min: -1000, max: 1000 })),
borderColor: 'rgb(53, 162, 235)',
backgroundColor: 'rgba(53, 162, 235, 0.5)',
},
],
};
export function App() {
return <Line options={options} data={data} />;
}
How can I achieve this with ChartJS ('react-chartjs-2')?
Yes -- ChartJS/react-chartjs-2 does support this. In order to do this, you need to:
Import/register the chart.js Filler plugin (Mentioned in the docs for Area Charts)
Set the tension of the line (to make the lines curve), and;
Set the fill options for the dataset.
Following these steps this will produce:
For example:
import React from "react";
import { Line } from "react-chartjs-2";
import {
Chart as ChartJS,
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend,
Filler // 1. Import Filler plugin
} from "chart.js";
import faker from "faker";
ChartJS.register(
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend,
Filler // 1. Register Filler plugin
);
export const options = {
responsive: true,
tension: 0.3 // 2. Set the tension (curvature) of the line to your liking. (You may want to lower this a smidge.)
};
const labels = ["January", "February", "March", "April", "May", "June", "July"];
export const data = {
labels,
datasets: [
{
label: "Dataset 1",
data: labels.map(() => faker.datatype.number({ min: 0, max: 500 })),
borderColor: "rgb(255, 99, 132)",
backgroundColor: "rgba(255, 0, 0)",
fill: {
target: "origin", // 3. Set the fill options
above: "rgba(255, 0, 0, 0.3)"
}
},
{
label: "Dataset 2",
data: labels.map(() => faker.datatype.number({ min: 0, max: 500 })),
borderColor: "rgb(53, 162, 235)",
backgroundColor: "rgba(53, 162, 235, 0.3)",
fill: "origin" // 3. Set the fill options
}
]
};
export function App() {
return <Line options={options} data={data} />;
}
Working CodeSanbox: https://codesandbox.io/s/chartjs-area-chart-p1o023?file=/App.tsx:817-846

react-chartjs-2 chart.js: How to make strokewidth of dougnut chart thin?

I am implementing one doughnut chart in react js by using react-chart.js-2 chart.js, but I want to customize it according to my requirements, I have done already some customization, but one I need to do is, to make the width of chart thin.
Current Image
enter image description here
Required Image
enter image description here
import React from "react";
import { Doughnut } from "react-chartjs-2";
const data = {
datasets: [
{
data: [8, 25, 2, 4, 3, 21, 2],
backgroundColor: [
"#FF6384",
"#36A2EB",
"#FFCE56",
"black",
"blue",
"red",
"purple",
],
borderColor: "transparent",
},
],
};
function App() {
return (
<div className="App">
{" "}
<h2>Doughnut Example</h2>
<Doughnut
data={data}
options={{
responsive: true,
maintainAspectRatio: false,
tooltips: false,
height: "2",
}}
/>
</div>
);
}
export default App;
Edit cutout property in options
let options = {
responsive: true,
cutout:"80%",
legend: {
display: false,
},
layout: {
padding: 10,
},
};
You need to define the cutoutPercentage option inside the chart options as follows:
<Doughnut
data={data}
options={{
responsive: true,
cutoutPercentage: 80,
...
}}
/>
cutoutPercentage: The percentage of the chart that is cut out of the middle (default value is 50).

Categories