Render React Component Inside of Highcharts Graph - reactjs

I'd like to be able to render a React Component inside of a HighCharts Graph. I'd like to render the component DatePicker inside my HighCharts Graph, rather than being above it like it currently is? I'm using the HighCharts Official React Wrapper, and this is what my code looks like:
function Graph(props) {
const [startDate, setStartDate] = useState(new Date('1969-11-19 PST'));
const [bx, setBx] = useState([]);
const [by, setBy] = useState([]);
const [bz, setBz] = useState([]);
async function getData(table, year, month, day) {
...
}
useEffect(() => {
...
}, [startDate])
var options = {
chart: {
events: {
load: function() {
this.showLoading();
setTimeout(this.hideLoading.bind(this), 2000);
}
}
},
lang: {
noData: "Awaiting for data"
},
rangeSelector: {
inputEnabled: false,
buttons: [
{
type: 'all',
text: '1d',
title: 'View 1 Day'
},
{
type: 'minute',
count: 10,
text: '10m',
title: 'View 10 minutes'
},
{
type: 'minute',
count: 1,
text: '1m',
title: 'View 1 minutes'
},
{
type: 'second',
count: 30,
text: '30s',
title: 'View 30 seconds'
},
]
},
chart: {
zoomType: 'x'
},
title: {
text: props.title
},
xAxis: {
type: 'datetime'
},
time: {
timezoneOffset: 8*60
},
series: [
{
marker: {
enabled: true,
radius: 2
},
color: 'red',
name: 'Bx',
pointStart: startDate.getTime(),
pointInterval: 1000,
data: bx // data has to be [x, y] pairs
},
{
marker: {
enabled: true,
radius: 2
},
color: 'blue',
name: 'By',
pointStart: startDate.getTime(),
pointInterval: 1000,
data: by
},
{
marker: {
enabled: true,
radius: 2
},
color: 'green',
name: 'Bz',
pointStart: startDate.getTime(),
pointInterval: 1000,
data: bz
}
]
}
const isValidDate = (date) => {
date.getTime();
const origDate = new Date('1969-11-19 PST');
const finalDate = new Date('1970-04-03 PST');
console.log("GET DATE", date.getTime()) // getting number day of month
const bool = origDate.getTime() <= date.getTime() && date.getTime() <= finalDate.getTime();
return bool;
}
return (
<React.Fragment>
<DatePicker
selected={startDate}
filterDate={isValidDate}
onChange={(date) => setStartDate(date)}
/>
<HighchartsReact
highcharts={Highcharts}
constructorType={'stockChart'}
options={options}
/>
</React.Fragment>
);
}
I see this example from the HighCharts React Official Wrapper Github, but I'm still a bit confused by it and am wondering if I could simply do the same thing with a functional component. https://codesandbox.io/s/1o5y7r31k3
I've made a codesandbox of my code here https://codesandbox.io/s/friendly-moon-y8guc

Related

Chartjs + Reactjs - Progressive Line chart can't show anything from my own dataset?

I am trying to get a progressive line chart working using the docs as a starting point.
Link to example
While I now have the sample code working after removing the Utils.CHART_COLORS and importing the easingEffects. I am trying to get my data to show up, I don't get any errors, which just doesn't work.
import { easingEffects } from "chart.js/helpers";
# This is in a separate file, I import it.
export const DemoData = [
{
"id": 1,
"date":,
"price":,
"mess":
},
{
"id": 1,
"date":"11/01/2022",
"price":"100",
"bp": "95",
"mess": "Hi"
},
{
"id": 2,
"date":"11/05/2022",
"price":"95",
"bp": "90",
"mess":"Hola"
},
{
"id": 3,
"date":"11/10/2022",
"price":"97",
"bp": "99",
"mess": "Dang"
},
]
# I have tried a bunch of different things, latest iteration
let easing = easingEffects.easeOutQuad;
let restart = false;
const totalDuration = 5000;
// const duration = (ctx) => easing(ctx.index / data.length) * totalDuration / data.length;
const delay = (ctx) => easing(ctx.index / data.length) * totalDuration;
const previousY = (ctx) => ctx.index === 0 ? ctx.chart.scales.y.getPixelForValue(100) : ctx.chart.getDatasetMeta(ctx.datasetIndex).data[ctx.index - 1].getProps(['y'], true).y;
const animation = {
x: {
type: 'number',
easing: 'linear',
duration: 5000,
from: NaN, // the point is initially skipped
delay: 2500
},
y: {
type: 'number',
easing: 'linear',
duration: 5000,
}
}
export const config_progressive = {
type: 'line',
data: {
labels: DemoData.map((data) => data.date),
datasets: [{
label: 'Stock Price',
data: DemoData.map((data) => data.price),
},
{
label: 'Purchase Price',
data: DemoData.map((data) => data.bp),
}
]
},
options: {
animation,
interaction: {
intersect: false
},
plugins: {
legend: false,
title: {
display: true,
text: () => easing.name
}
},
scales: {
x: {
type: 'time',
time: {
unit: 'day',
parser: 'mm.dd.yyyy'
}
}
}
}
};
The same DemoData in a simple line chart works without a problem.
In the output of the above code. The Y axis seems to have the right numbers, the "X axis" doesn't show dates. And the data doesn't show up at all.
I wasn't able to find a resource to learn how to proceed/troubleshoot.

ChartJS - Why is the transition on the first dataset bad?

So I have react-datepicker to choose the dates of my data, the data that is returned looks like this:
{clicks: 6, date: "2022-05-15", link: "instagram"},
{clicks: 5, date: "2022-05-15", link: "google"}...
On load and every change in the datePicker, I have this function which sets the data variables, the date will be moment():
const onChangeClick = (dates: any) => {
const [start, end] = dates;
setStartDateClick(start);
setEndDateClick(end);
if (start & end) {
let dates = {
dateFrom: moment(start).format('YYYY-MM-DD'),
dateTo: moment(end).format("YYYY-MM-DD")
}
_statisticsService.getClickStats(dates).then((response: any) => {
response.data.map((e: any) => {
clicksData[e?.link].push(e)
})
setInstaDataClick(clicksData['instagram'].map((e: any) => {
return { clicks: e.clicks, date: moment(e.date) }
}))
setFacebookDataClick(clicksData['facebook'].map((e: any) => {
return { clicks: e.clicks, date: moment(e.date) }
}))
setGoogleDataClick(clicksData['google'].map((e: any) => {
return { clicks: e.clicks, date: moment(e.date) }
}))
setTripadvisorDataClick(clicksData['tripadvisor'].map((e: any) => {
return { clicks: e.clicks, date: moment(e.date) }
}))
setWebsiteDataClick(clicksData['website'].map((e: any) => {
return { clicks: e.clicks, date: moment(e.date) }
}))
})
setLabelsClick(getDaysArray(clicksData[0]?.date, clicksData[clicksData.length - 1].date))
}
};
And later I use this values in the datasets:
const data = {
labels: labelsClick,
datasets: [
{
label: 'Instagram',
data: instaDataClick,
borderColor: '#c32aa3',
backgroundColor: '#c32aa3',
},
{
label: 'Facebook',
data: facebookDataClick,
borderColor: '#1877f2',
backgroundColor: '#1877f2',
},
{
label: 'Google',
data: googleDataClick,
borderColor: '#ea4335',
backgroundColor: '#ea4335',
},
{
label: 'Tripadvisor',
data: tripadvisorDataClick,
borderColor: '#34e0a1',
backgroundColor: '#34e0a1',
},
{
label: 'Website',
data: websiteDataClick,
borderColor: '#010101',
backgroundColor: '#010101',
},
],
};
And at the end this is how I preview the Line chart
<div className='datepicker-container'>
<DatePicker
onChange={onChangeClick}
startDate={startDateClick}
endDate={endDateClick}
selectsRange
placeholderText='Select Date'
isClearable
/>
</div>
<div className='chart'>
<Line options={options} data={data} />
</div>
The options for this line look like this, x axis is the date and y is the clicks:
const options: ChartOptions<'line'> = {
responsive: true,
scales: {
y: {
title: {
display: true,
text: 'Date'
},
ticks: {
precision: 0,
}
},
x: {
type: 'time',
title: {
display: true,
text: "Date"
},
time: {
unit: 'day',
stepSize: 1,
displayFormats: {
day: "MMM DD"
}
}
},
},
parsing: {
xAxisKey: 'date',
yAxisKey: 'clicks',
},
plugins: {
legend: {
position: 'top',
},
title: {
display: true,
text: 'Click statistics',
},
},
};
And now THE PROBLEM:
On first load, the first line in the dataset, in this case Instagram, shows like this:
The instagram line has a different animation, what could be the problem?
[edit]: Changing the animation in options won't affect the instagram line, it will still come from the left, depending on the animation, it will come either slower or faster, but always from left.
For anyone who has the same issue in the future, here is the solution:
The problem with my code was that the first state of the instaDataClick variable was an empty array, it should have a date property, because the x axis is the date.
so the variable should look something like this:
const initialStartDate = new Date(moment().subtract(10, 'd').format('YYYY-MM-DD'))
const initialEndDate = new Date(moment().format('YYYY-MM-DD'))
const [instaDataClick, setInstaDataClick] = useState(
getDaysArray(initialStartDate.toString(), initialEndDate.toString()).map((e)=>{
return {clicks: null, date: e}
})
)
the function getDaysArray:
const getDaysArray = function (start: any, end: any) {
for (var arr = [], dt = new Date(start); dt <= new Date(end); dt.setDate(dt.getDate() + 1)) {
arr.push(new Date(dt).toString().substr(4, 6));
}
return arr;
};
And by doing this, we're setting the initial position of the line.

react-graph-vis - Grapg is not re rendering even ofter state changes

When I try to update the state on the hover event, the actual state value is getting changed but the graph is not re-rendering.
in the console, I am able to see the node label is changed to sample. but the graph is not rerendering.
Here is my react function based component.
import React, { useEffect, useState } from 'react';
import Graph from 'react-graph-vis';
import './vis-network.css';
function RelationGraph1() {
const [graph, setGraph] = useState({
nodes: [
{
id: 1,
label: 'Node 1',
title: '',
},
{ id: 2, label: 'Node 2', title: '' },
{ id: 3, label: 'Node 3', title: '' },
{ id: 4, label: 'Node 4', title: '' },
{ id: 5, label: 'Node 5', title: '' },
],
edges: [
{ from: 1, to: 2 },
{ from: 1, to: 3 },
{ from: 2, to: 4 },
{ from: 2, to: 5 },
],
});
const options = {
layout: {
hierarchical: false,
},
edges: {
color: '#1D1D1D',
},
interaction: {
hover: true,
navigationButtons: true,
tooltipDelay: 0,
},
nodes: {
borderWidth: 0,
borderWidthSelected: 0,
color: '#0262C4',
shape: 'circle',
size: 1,
shadow: {
enabled: true,
color: 'rgba(0,0,0,0.5)',
size: 10,
x: 5,
y: 5,
},
font: {
color: '#fff',
size: 13,
bold: {
mod: 'bold',
},
},
},
};
const events = {
select: function (event) {
var { nodes, edges } = event;
console.log('Selected nodes:');
console.log(nodes);
console.log('Selected edges:');
console.log(edges);
},
showPopup: (id) => { // node id
const data = graph.nodes.map((el) => {
if (el.id === id) {
el.label = `sample node name`;
}
return el;
});
setGraph({ ...graph, nodes: data });
},
};
return (
<Graph
graph={graph}
options={options}
events={events}
style={{ height: '450px' }}
/>
);
}
export default RelationGraph1;
Really Appriciate for the help. Thanks !
I was able to update the label in hoverNode event like this:
hoverNode: (e) => {
const data = graph.nodes.map((el) => {
if (el.id === e.node) return { ...el, label: "sample node name" };
else return el;
});
const temp = { ...graph };
temp.nodes = data;
setGraph(temp);
},
Sample: https://codesandbox.io/s/long-bird-4h444?file=/src/App.js:1235-1501

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.

How can I display the current value from a chart?

I am new to React and I work on a small project basically, I have a chart and I just want to display the current value from the chart.
For example, I have a chart with 4 random values:[5,2,5,1], so I want to have displayed the current value below the chart like first is 5, second is 2 and so on.
Here is my part of code:
class App extends React.Component {
addPoint = (point) => {
currentData = this.state.options.series[0].data
this.setState({
options: {
series: [
{ data: [...currentData, point]}
]
}
});
}
constructor(props) {
super(props);
this.internalChart = undefined;
this.dataStream = new DataStream();
this.dataStream.setUpdateCallback(this.addPoint);
this.state = {
options: {
chart: {
events: {
load: function () {
}
}
},
time: {
useUTC: false
},
rangeSelector: {
buttons: [{
count: 1,
type: 'minute',
text: '1M'
}, {
count: 5,
type: 'minute',
text: '5M'
}, {
type: 'all',
text: 'All'
}],
inputEnabled: false,
selected: 2
},
title: {
text: 'Live random data'
},
exporting: {
enabled: false
},
series: [{
name: 'Random data',
data: [[(new Date()).getTime(), 0]]
}]
}
};
}
render() {
return (
<HighchartsReact
constructorType={"stockChart"}
highcharts={Highcharts}
options={this.state.options}
/>
);
}}
Based on your snippet code, try to make random method by using function
Math.floor(Math.random() * Math.floor(max))
And then assign the options to HighchartsReact,
Full code on sandbox: https://codesandbox.io/s/headless-dream-0lzj1

Resources