I am using chart.js in reaction to create line chart. I want to show the day and month data like Aug 25, Jul 16. I don't know how to change the format of this data downloaded from the API. Please help. Here is my code
thank you for the hints
Is there a proper way to format dates for data labels in Chart.JS?
import axios from 'axios';
import { useParams } from 'react-router-dom';
import {
Chart as ChartJS,
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend,
} from 'chart.js';
import { Line } from 'react-chartjs-2';
ChartJS.register(
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend
);
const rate = axios.create({
baseURL: 'http://api.nbp.pl/api/exchangerates/rates/a/',
});
const Chart = () => {
const [post, setPost] = useState();
const { id } = useParams();
useEffect(() => {
async function getPost() {
const response = await rate.get(`/${id}/last/10/?format=json`);
setPost(response.data);
}
getPost();
}, [id]);
const data = {
type: 'line',
labels: post?.rates?.map((x) => x.effectiveDate),
datasets: [
{
label: `Ostatnie 10 odczytów`,
data: post?.rates?.map((y) => y.mid),
lineTension: 0.1,
backgroundColor: 'rgba(15, 174, 150)',
borderColor: 'rgba(15, 174, 150)',
gridLines: 'false',
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: 'rgba(15, 174, 150)',
pointBackgroundColor: '#fff',
pointBorderWidth: 1,
pointHoverRadius: 5,
pointHoverBackgroundColor: 'rgba(15, 174, 150)',
pointHoverBorderColor: 'rgba(220,220,220,1)',
pointHoverBorderWidth: 2,
pointRadius: 1,
pointHitRadius: 10,
},
],
options: {
responsive: true,
},
};
return (
<div
style={{
width: '800px',
height: '800px',
margin: '0px auto',
paddingTop: '500px',
}}
>
<Line data={data} />
</div>
);
};
export default Chart;
Welcome, Veronica! If you don't want to use a third-party package, I would advise working with the Date type along with the Intl.DateTimeFormat object. Once you've cast to Date, you can build the desired string.
post?.rates?.map(x => {
date = new Date(x.effectiveDate);
return new Intl.DateTimeFormat('en-US', {
month: 'short',
day: 'numeric',
}).format(date);
});
Hi I think you can use moment or dayjs(same stuff and moment since its depricated suggested dayjs) for this like
post?.rates?.map((x) => moment(x.effectiveDate).format('the format you want))
Related
I'm making a line chart in sveltekit, using the svelte-chartjs package. The data for this chart is a set of timestamps, so I have to use a date adapter for chart.js.
The adapter I'm using is chartjs-adapter-luxon, and it seems to work, it spaces everything out correctly, except it has the wrong labels.
The labels are all showing one specific day: Jan 20, 1970, but my data has timestamps from several weeks in it, and none of them are from 1970. It's also suspicious that they're so close to the Unix epoch.
I can't figure it out, please help
My relevant code:
<script>
export let data
import { Line } from 'svelte-chartjs';
import 'luxon'
import 'chartjs-adapter-luxon'
import {
Chart,
Tooltip,
Legend,
BarElement,
CategoryScale,
LinearScale,
LineElement,
PointElement,
TimeScale,
} from 'chart.js';
Chart.register(
Tooltip,
Legend,
BarElement,
CategoryScale,
LineElement,
PointElement,
LinearScale,
TimeScale,
);
let graphdata = graph()
let graphoptions = {
scales: {
x: {
type: 'time',
time: {
unit: 'day',
displayFormats: {
second: 'MMM d, yyyy'
}
},
adapters: {
date: {
zone: 'UTC+6'
}
},
}
},
responsive: true,
maintainAspectRatio: false,
}
function graph() {
if (data.graph) {
let labels = []
for (let i = 0; i < data.graph.timestamp.length; i++) {
let timestamp = data.graph.timestamp[i]
const myDateTime = new Date(timestamp * 1000)
const myDateTimeISO = myDateTime.toISOString()
labels.push(new Date(myDateTimeISO))
}
let graphdata = {
labels: data.graph.timestamp,
datasets: [
{
label: 'Followers',
data: data.graph.followers,
backgroundColor: ["rgb(30 58 138 / 1)"],
borderWidth: 2,
borderColor: "#e5e7eb",
hoverBackgroundColor: ["rgb(30 58 138 / 1)"],
hoverBorderColor: "#e5e7eb",
},
{
label: 'Following',
data: data.graph.following,
backgroundColor: ["#818cf8"],
borderWidth: 2,
borderColor: "#e5e7eb",
hoverBackgroundColor: ["#818cf8"],
hoverBorderColor: "#e5e7eb",
},
{
label: 'Posts',
data: data.graph.posts,
backgroundColor: ["rgb(253 224 71 / 1)"],
borderWidth: 2,
borderColor: "#e5e7eb",
hoverBackgroundColor: ["rgb(253 224 71 / 1)"],
hoverBorderColor: "#e5e7eb",
},
],
};
return graphdata
} else {
return null
}
}
</script>
<Line data={graphdata} options={graphoptions} />
I want to implement a simple Gantt Chart using 'react-chartjs-2'.
I want Courses on Y axis, and Time-slots(HH:mm) in X axis. I also want to set Duration of each entry. I did This -
import React from 'react'
import UniNavbar from './UniNavbar';
import {UserData} from '../components/Chart/Data';
import { Bar } from 'react-chartjs-2';
import 'chartjs-adapter-date-fns';
import {
Chart as ChartJS,
CategoryScale,
LinearScale,
TimeScale,
BarElement,
Title,
Tooltip,
Legend,
} from 'chart.js';
ChartJS.register(
TimeScale,
CategoryScale,
LinearScale,
BarElement,
Title,
Tooltip,
Legend
);
export const options = {
indexAxis: 'y',
elements: {
bar: {
},
},
scales: {
x:{
min: '00:00',
type: 'time',
time:{
unit:'hour',
displayFormats: {
hour: 'HH:mm'
},
},
},
},
responsive: true,
plugins: {
legend: {
position: 'right',
},
title: {
display: true,
text: 'Chart.js Horizontal Bar Chart',
},
},
};
const labels = ['CSE150', 'CSE331', 'IPE120D', 'CSE333', 'PHY203D', 'BUS201D', 'EEE303D'];
export const data = {
labels,
datasets: [
{
label: 'Dataset 1',
data: [
['02:00','00:40'],
['02:00','00:40'],
['02:00','00:40'],
['02:00','00:40'],
['02:00','00:40'],
['02:00','00:40'],
],
backgroundColor: [
'rgba(255, 26, 104, 0.2)',
],
borderColor: [
'rgba(255, 26, 104, 1)',
],
barPercentage: 0.2,
},
],
};
const Schedules = () => {
return (
<div>
<UniNavbar/>
Schedules
<Bar options={options} data={data} />
</div>
)
}
In each data, I want to enter starttime and endtime, according to that, I want entries on the chart.
Is my data definition wrong here?
There was no output in the chart of each data entry(HH: mm). What am I doing wrong here?
I'm new and practicing react.js.
I'm trying to update the content of array with useState by clicking a send-button, but it doesn't work as I expect.
Below is problem I'm having. Idk to add date and number in a row.
enter image description here
also, below is what I expect.
enter image description here
code:
import React, { useState, useRef } from 'react';
import classes from '../style/LineChart.module.css'
import { Button, Input } from '#chakra-ui/react';
import { Line } from 'react-chartjs-2'
import {
Chart as ChartJS,
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend,
} from "chart.js";
ChartJS.register(CategoryScale, LinearScale, PointElement, LineElement, Title,
Tooltip, Legend);
const LineChart = () => {
const [numData, setNumData] = useState([0]);
const [date, SetDate] = useState(['']);
const calVal = useRef(null);
const chooseDate = useRef(null);
const onClick = () => {
setNumData([calVal.current.value]);
calVal.current.value = '';
SetDate([chooseDate.current.value]);
// SetDate([...date, chooseDate.current.value])
chooseDate.current.value = '';
}
const data = {
labels: [date],
datasets: [
{
label: 'How many todos can you achieve?',
fill: true,
lineTension: 0.1,
backgroundColor: 'rgba(75,192,192,0.4)',
borderColor: 'rgba(75,192,192,1)',
borderCapStyle: 'round',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'square',
pointBorderColor: 'rgba(75,192,192,1)',
pointBackgroundColor: '#eee',
pointBorderWidth: 10,
pointHoverRadius: 5,
pointHoverBackgroundColor: 'rgba(75,192,192,1)',
pointHoverBorderColor: 'rgba(220,220,220,1)',
pointHoverBorderWidth: 1,
pointRadius: 1,
pointHitRadius: 10,
data: [numData]
}
]
};
const checkOfDelete = () => {
let result = window.confirm('Reset. ok?')
if(result) {
console.log('Delete.');
} else {
alert('fail.')
}
};
return (
<div mt='2'>
<Line data={data}/>
<Input className={classes.input} ref={chooseDate} variant='outline' w='40%' ml='30%' mb='3' mt='3' borderRadius='15px' type='text' label='date' placeholder='Date'/>
<Input className={classes.input} ref={calVal} variant='outline' w='54%' ml='23%' mb='3' borderRadius='15px' type='number' label='number' placeholder='How many?'/>
<br/>
{data.labels.length < 8 ? <Button colorScheme='teal' ml='21%' mr='2' onClick={onClick}>Send</Button> : <p>date is full.</p>}
<Button colorScheme='teal' onClick={checkOfDelete} >Reset</Button>
</div>
)
};
export default LineChart;
To work well, I've tried this way.
const data = {
labels: [calVal.current.value ,...date],
datasets: [
{
label: 'How many todos can you achieve?',
fill: true,
lineTension: 0.1,
backgroundColor: 'rgba(75,192,192,0.4)',
borderColor: 'rgba(75,192,192,1)',
borderCapStyle: 'round',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'square',
pointBorderColor: 'rgba(75,192,192,1)',
pointBackgroundColor: '#eee',
pointBorderWidth: 10,
pointHoverRadius: 5,
pointHoverBackgroundColor: 'rgba(75,192,192,1)',
pointHoverBorderColor: 'rgba(220,220,220,1)',
pointHoverBorderWidth: 1,
pointRadius: 1,
pointHitRadius: 10,
data: [chooseDate.current.value,...numData]
}
]
};
but if this, I got error like: "Uncaught TypeError: Cannot read properties of null (reading 'value')"
Can someone please help me? I am sorry if it is very basic but I am only starting out..
You are defining the values as null. You only update the values in the onClick function.
const calVal = useRef(null);
const chooseDate = useRef(null);
add below the above code
calVal.current.value = ''
chooseDate.current.value = ''
I am trying to generate a scatterplot using chartJS. The plot wont graph.
When i feed in data manually by declaring the data, it works fine,
var scatter = [
{ x: 65, y: 75 },
{ x: 59, y: 49 },
{ x: 80, y: 90 },
{ x: 81, y: 29 },
{ x: 56, y: 36 },
{ x: 55, y: 25 },
{ x: 40, y: 18 },
]
but when I get the data via an API call and push the data to the array, it won't work. Any suggestions? I suspect its to do with how data is pushed onto the array but not sure what's wrong.
Thank you
Minimum solution below
import React, { useEffect, useState } from 'react';
import axios from 'axios';
function App() {
const [scatterData, setScatterData] = useState({});
const chart = () => {
var scatter = [];
axios.get('http://dummy.restapiexample.com/api/v1/employees')
.then(res => {
let temp = res.data.data
temp.forEach( i=> {
let age = parseInt(i.employee_age)
let salary = parseInt(i.employee_salary)
scatter.push({"x": age,
"y": salary})
})
}).catch(err => {
console.log(err)
})
console.log(scatter)
setScatterData({
datasets: [
{
label: 'test',
fill: true,
backgroundColor: 'rgba(75,192,192,0.4)',
pointBorderColor: 'rgba(75,192,192,1)',
pointBackgroundColor: '#fff',
pointBorderWidth: 1,
pointHoverRadius: 10,
pointHoverBackgroundColor: 'rgba(75,192,192,1)',
pointHoverBorderColor: 'rgba(220,220,220,1)',
pointHoverBorderWidth: 2,
pointRadius: 3,
pointHitRadius: 10,
data: scatter,
backgroundColor: [
'rgba(75,192,192,0.6)'
],
borderWidth: 4
}
]
});
}
useEffect(() ={
chart()
},[])
return (
<div className ="container-fluid">
<div class="row">
<div className ="col-md-12">
<Scatter data={scatterData}/>
</div>
</div>
</div>
)
};
Try calling the update method on your chart object/instance after you pushed all the data from the api to your scatter array
I use chart.js with React and I can't figure out why the line chart doesn't work with type: 'time', maybe I could be missing something:
Chart.js CodeSandbox
import React from "react";
import { Line } from "react-chartjs-2";
const startDate = new Date(2020, 4, 20);
const json = '{"responses":[{"count":"73","rows":[{"values":["1"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["1"]},{"values":["6"]},{"values":["7"]},{"values":["5"]},{"values":["8"]},{"values":["9"]},{"values":["2"]},{"values":["1"]},{"values":["1"]},{"values":["1"]},{"values":["6"]},{"values":["3"]},{"values":["0"]},{"values":["20"]},{"values":["9"]},{"values":["3"]},{"values":["2"]},{"values":["1"]},{"values":["13"]},{"values":["3"]},{"values":["13"]},{"values":["13"]},{"values":["7"]},{"values":["12"]},{"values":["0"]}]}]}';
const values = JSON.parse(json).responses[0].rows.map(row => row.values[0]);
const options = {
legend: {
display: false
},
hover: {
mode: "index",
intersect: false,
animationDuration: 0
},
scales: {
yAxes: [{ position: "right" }],
xAxes: [
{
gridLines: { display: false },
type: "time",
time: {
parser: "MMM D",
unit: "day",
unitStepSize: 5,
displayFormats: {
day: "MMM D"
}
},
ticks: {
min: startDate, //May 20
max: new Date()
}
}
]
},
tooltips: {
mode: "x-axis"
}
};
const data = {
datasets: [
{
label: "data",
fill: false,
data: values,
backgroundColor: "pink",
borderWidth: 2,
lineTension: 0,
borderColor: "pink",
hoverBorderWidth: 2,
pointBorderColor: "rgba(0, 0, 0, 0)",
pointBackgroundColor: "rgba(0, 0, 0, 0)",
pointHoverBackgroundColor: "#fff",
pointHoverBorderColor: "pink",
showLine: true
}
]
};
const LineChart = () => {
return (
<div style={{ maxWidth: 1024, margin: "32px auto" }}>
<Line data={data} options={options} />
</div>
);
};
export default LineChart;
You should generate specific dataset like this:
const values = JSON.parse(json).responses[0].rows.map((row, index) => {
let date = new Date(2020, 4, 20);
date.setDate(startDate.getDate() + index)
return {
y: row.values[0],
x: date
};
});
example