React Js Plotly Remove Time Gaps In Graph - reactjs

I am trying to plot stock data, but there are gaps in the graph where data for these time periods don't exist. How do I remove these gaps? I found that there is an update_xaxes function but I'm not sure how to apply it to my case.
My code:
import React, { useState, Component, useEffect } from "react";
import Plot from 'react-plotly.js';
export const Chart = () => {
return (
<div>
<Plot
data={[
{
x: data['dates'],
y: data['open_price'],
type: 'scatter'
}
]}
layout={{
autosize: false,
width: 1500,
height: 800,
xaxis: {
color: 'red',
rangebreaks: {
bounds: ["sat", "mon"],
values: ["2015-12-25", "2016-01-01"],
bounds: [17, 9], pattern: "hour"
}
}
}}
/>
</div>
)
}

react-ploty allows configuring the underlying ploty configuration through props. The data props you're already using accepts the same Traces Object than regular ploty. Therefore you can use rangebreaks as suggested by #r-beginners to achieve the desired effect.

xaxis: {
color: 'red',
rangebreaks: [
{ bounds: ["sat", "mon"] },
{
values: ["2019-12-25"]
},
{ bounds: [17, 9], pattern: "hour" }
]
}
I fixed it by making rangebreaks an array.

Related

How to limit xAxes and yAxes in React Chart JS?

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.

ReferenceError: ResizeObserver is not defined with nivo and NextJS

I want to use nivo with Next but when I load the page containing a pie chart made with nivo, I get this error: ReferenceError: ResizeObserver is not defined.
My Pie.js component:
import { ResponsivePie } from "#nivo/pie";
export const data = [
{
id: "c",
label: "c",
value: 80,
color: "hsl(8, 70%, 50%)",
},
{
id: "lisp",
label: "lisp",
value: 188,
color: "hsl(122, 70%, 50%)",
},
{
id: "go",
label: "go",
value: 161,
color: "hsl(111, 70%, 50%)",
},
];
export default function MyPie({ data }) {
return (
<ResponsivePie
data={data}
margin={{ top: 40, right: 80, bottom: 80, left: 80 }}
innerRadius={0.5}
padAngle={0.7}
cornerRadius={3}
activeOuterRadiusOffset={8}
borderWidth={1}
borderColor={{ from: "color", modifiers: [["darker", 0.2]] }}
arcLinkLabelsSkipAngle={10}
arcLinkLabelsTextColor="#333333"
arcLinkLabelsThickness={2}
arcLinkLabelsColor={{ from: "color" }}
arcLabelsSkipAngle={10}
arcLabelsTextColor={{ from: "color", modifiers: [["darker", 2]] }}
defs={[
{
id: "dots",
type: "patternDots",
background: "inherit",
color: "rgba(255, 255, 255, 0.3)",
size: 4,
padding: 1,
stagger: true,
},
{
id: "lines",
type: "patternLines",
background: "inherit",
color: "rgba(255, 255, 255, 0.3)",
rotation: -45,
lineWidth: 6,
spacing: 10,
},
]}
/>
)
};
My chart.js page:
import MyPie, { data } from "../components/Pie";
import homeStyles from "../styles/Home.module.css";
function Chart() {
return (
<div className={homeStyles.divchart}>
<MyPie data={data}/>
</div>
);
};
export default Chart;
This error only appears when using ResponsivePie and not Pie. I also tried to make it work with a React project but though I don't get this error, Nothing seems to be displayed.
Edit:
After some investigations, it looks like there is something wrong with #nivo/core 0.79.0 dependency. We should open an issue on the GitHub repo. I made some changes to check whether it is caused by my version of Next.js but the bug occurs only with #nivo/core 0.79.0.
It turns out this was the result of a bug introduced in version 0.79.0, which was fixed in https://github.com/plouc/nivo/pull/1886.
You should update #nivo/core to 0.79.1.
It looks like #nivo/pie is not compatible with Next.js server-side rendering as it utilizes Web APIs (ResizeObserver).
To avoid importing MyPie (and subsequently ResponsivePie) on the server, you can dynamically import it on the client-side only using next/dynamic with ssr: false.
import dynamic from "next/dynamic";
import { data } from "../components/Pie";
import homeStyles from "../styles/Home.module.css";
const MyPie = dynamic(() => import("../components/Pie"), {
ssr: false
})
function Chart() {
return (
<div className={homeStyles.divchart}>
<MyPie data={data}/>
</div>
);
};
export default Chart;
It's likely that code is being run on server side (SSR), and ResizeObserver doesn't exist there. You should try to make sure that your code only executes when on client side.
It's hard for me to tell you how as I don't know what your setup is. You can likely just add a check to only run that part of the code if ResizeObserver is defined.
I hope at least this points you in the right direction.

How to fill background color in ant-design charts with y-axis value condition

So I'm currently using ant-design charts to plot data which I pull from Django to React. What I wanna do is to fill colors to the background according to the y-axis values. For eg, I want the background color for 15-18 to be red, 18-20 to be yellow, 20-25 to be green and so on and so forth. Here's a screenshot of what I want to achieve:
and what I have so far is a very simple Line chart:
import React from "react";
import { Line } from "#ant-design/charts";
const Graph = (props) => {
var config = {
data: props.data,
padding: "auto",
xField: "Hour",
yField: "Measurement",
yAxis: {
minLimit: 15,
maxLimit: 30,
tickCount: 16,
},
};
return <Line {...config} />;
};
export default Graph;
I've tried finding articles or guides online but is unable to find any. Any help would be appreciated thank you so much!
You can use Region annotations
https://g2plot.antv.vision/en/docs/api/plots/tiny-area#-region-annotation
var config = {
...
annotations: [
{
type: 'region',
start: ['min', 15]
end: ['max', 18],
style: {
fill: '#ff0000'
}
},
{
type: 'region',
start: ['min', 18]
end: ['max', 20],
style: {
fill: '#00ffff'
}
}
...
]
}

Line Chart Js x-axis values all 0 on React

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';

Pie Chart Label is not visible in ReactJS

I am trying to create a Pie Chart dashboard. Chart is getting drawn based on the value, but the legend is not getting displayed. I have tried the label as below.
Chart
Summary.js:
import React, { Component } from 'react';
import PieChart from 'react-minimal-pie-chart';
class Summary extends Component {
render()
{
return(
<PieChart className="chart-style" x={50} y={60} outerRadius={100} innerRadius={50}
data={[
{ value: 11, color: '#E38627',label: 'New' },
{ value: 12, color: '#C13C37',label: 'Closed' },
{ value: 8, color: '#6A2135',label: 'Reopened' },
]}
/>
);
}
}
export default Summary;
Adding this works for me.
label={(props) => { return props.dataEntry.title;}}
Example
<PieChart
label={(props) => { return props.dataEntry.title;}}
data={[{ title: "One", value: 10, color: "#E38627" },
{ title: "Two", value: 15, color: "#C13C37" },
{ title: "Three", value: 20, color: "#6A2135" },
]}
/>
Its works at least for display labels, but you can customize it for showing percentage as well.
A good way to solve it is to provide a label function
<PieChart ...
label={props => { return props.data[props.dataIndex].label;}}
/>
You can also just provide label={true} but then it will show te value not the label in the data array.

Resources