How to use data from database in react-chartjs-2 dataset - arrays

I have a chart built with react-chartjs-2. The chart displays when I enter the values for data directly in the datasets like this.
datasets: [
{
label: "Active Countries",
backgroundColor: gradientFill,
borderColor: "#2CA8FF",
pointBorderColor: "#FFF",
pointBackgroundColor: "#2CA8FF",
pointBorderWidth: 2,
pointHoverRadius: 4,
pointHoverBorderWidth: 1,
pointRadius: 4,
fill: true,
borderWidth: 1,
data: [80, 99, 86, 96, 123, 85, 100, 75, 88, 90, 123, 155]
}
]
However, I want to replace the value of the data in the datasets with a monthly transaction derived from transactions recorded in my database. The code for my total transaction for each month Jan to Dec ( One for each month) is like this.
const januaryTransactions = transactions.filter(i => {
const date = new Date(i.date);
return date.getMonth() === January && date.getYear() === relevantYear;
}).reduce((prev, curr) => prev + parseFloat(curr.amount), 0)
My question is how do I replace for example the value at in index 0 [80, 99, 86, 96, 123, 85, 100, 75, 88, 90, 123, 155] which is 80 with januaryTransactions .
Any Pointers are mostly appreciated!!

Related

pointClick listener on stacked data

curious if there is a way to get the proper index on stacked data (such as a Waterfall diagram) from AnyChart. Using the below on a waterfall gets you the same index for anything click on in a specific stack, when really there should be two index numbers (the column index and the element index within that column).
// add a listener
chart.listen("pointClick", function(e){
var index = e.iterator.getIndex();
});
Thanks
You can get the element index through e.target.getIndex().
anychart.onDocumentReady(() => {
let data = anychart.data.set([
["Start", 23, 30, 21],
["Jan", 22, 22, 54],
["Feb", -46, 45, -32],
["Mar", -91, -30, -28],
["Apr", 37, -27, 36],
["May", -24, 62, -48],
["Jun", 55, 40, -29],
["Jul", 31, 33, 41],
["Aug", -25, -46, 36],
["Sep", 42, 23, 22],
["Oct", 67, -44, -40],
["Nov", -24, -31, 37],
["Dec", 51, 28, 25],
["End", { isTotal: true }, { isTotal: true }, { isTotal: true }],
]);
let seriesData_1 = data.mapAs({ x: 0, value: 1 }),
seriesData_2 = data.mapAs({ x: 0, value: 2 }),
seriesData_3 = data.mapAs({ x: 0, value: 3 });
let chart = anychart.waterfall();
let series1 = chart.waterfall(seriesData_1),
series2 = chart.waterfall(seriesData_2),
series3 = chart.waterfall(seriesData_3);
chart.labels().position("center");
chart.labels().fontColor("white");
chart.listen("pointClick", e => {
let columnIndex = e.iterator.getIndex(),
elementIndex = e.target.getIndex(); // <--- HERE
console.log(`Column index: ${columnIndex}`);
console.log(`Element index: ${elementIndex}`);
});
chart.container("container");
chart.draw();
});
#container {
width: 100%;
height: 350px;
}
<script src="https://cdn.anychart.com/releases/8.11.0/js/anychart-core.min.js"></script>
<script src="https://cdn.anychart.com/releases/8.11.0/js/anychart-waterfall.min.js"></script>
<div id="container"></div>
The example above is a modified version of what you can find there: Waterfall Chart | Basic Charts | AnyChart Documentation

React ApexCharts: Applying forecastDataPoints to a single series?

I am using ApexCharts in React to create a line chart with two series, representing 'Current Year' and 'Last Year' for direct comparison. The Y axis displays a percentage and the X axis runs 'Jan' to 'Dec', with monthly data points.
I am new to React and struggling to find how to apply the 'forecastDataPoints' property to just the 'Current Year' series. I can easily apply it to both series by using it within 'options' but this applies it to both series:
options: {
chart: {
height: 350,
type: 'line',
},
colors: ['#172774','#F1B44C'],
forecastDataPoints: {
count: 3
},
I assumed the way to achieve this is to put the forecastDataPoints property within the series, but this doesn't work:
this.state = {
series: [{
name: 'Curremt Year',
data: [11, 24, 46, 62, 54, 52, 61, 67, 71, 78, 81, 83],
forecastDataPoints: {
count: 3
},
},
{
name: 'Last Year',
data: [5, 14, 12, 22, 25, 31, 39, 42, 45, 51, 52, 51],
},

Updating ReactJS UI with loop data one after another

I have recently created grid in UI and I want to show the complete flow of motion for all the points given by the array. However, the UI was updated with the value in the last loop.
For ex: position = [1, 2, 3]
At the initial point '1', there is a circle
then the circle move to 2 -> then 3
Instead, moving from 1 to 3
Can anybody help me to achieve this?
My whole class is as follows,
import React, { useEffect, useState } from 'react';
import { Button } from 'reactstrap';
import { motion } from "framer-motion";
import './style.css';
import Grid from './grid'
class Game extends React.Component {
constructor(props) {
super(props);
this.state = {
idOfBegin: "1",
position: 0,
xAxis: 0,
yAxis: 0,
position: [],
arrOfObj: [100, 99, 98, 97, 96, 95, 94, 93, 92, 91,
81, 82, 83, 84, 85, 86, 87, 88, 89, 90,
80, 79, 78, 77, 76, 75, 74, 73, 72, 71,
61, 62, 63, 64, 65, 66, 67, 68, 69, 70,
60, 59, 58, 57, 56, 55, 54, 53, 52, 51,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50,
40, 39, 38, 37, 36, 35, 34, 33, 32, 31,
21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
20, 19, 18, 17, 16, 15, 14, 13, 12, 11,
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
]
};
}
start = () => {
var a = document.getElementById("3");
var codinates = a.getBoundingClientRect();
var x = codinates.left + 35;
var y = codinates.top + 5;
console.log(x, y);
this.setState({ xAxis: x });
this.setState({ yAxis: y });
}
loadPosition = async (event) => {
fetch('api/groups')
.then(response => response.json())
.then(data => {
//console.log('======== ' +data);
//groups.map(group => setPosition(group));
this.setState({ position: data });
});
}
getCellValue = async (event) => {
this.loadPosition();
this.state.position.forEach(p => {
console.log('====== ' + p);
if (p != null) {
var a = document.getElementById(p);
var codinates = a.getBoundingClientRect();
var x = codinates.left + 35;
var y = codinates.top + 5;
//console.log(x,y);
this.setState({ xAxis: x });
this.setState({ yAxis: y });
}
});
}
componentDidMount() {
this.setState({ xAxis: 45 });
this.setState({ yAxis: 905 });
}
render() {
return (
<div>
<div className="grid"><Grid arrOfObj={this.state.arrOfObj} />
<motion.div animate={{ x: this.state.xAxis, y: this.state.yAxis }}
transition={{ type: "tween", duration: 1 }}
></motion.div>
</div>
<div className="control">
<Button color="primary" onClick={() => this.start()}>Start</Button>
<Button color="primary" onClick={() => this.getCellValue()}>Roll Dice</Button>
</div>
</div>
);
}
}
export default Game;

how to get the selected color

I used colorPickr to build three color select components. The problem is that I can't find the variable that stores the selected color in order to use it and store it into the state..
I tried to use the event "save" that is mentionned in the documentation : https://github.com/Simonwep/pickr
export default class ColorPicker extends Component {
componentDidMount(){
const pickr = Pickr.create({
el: '.color-picker',
theme: 'classic',
swatches: [
'rgba(244, 67, 54, 1)',
'rgba(233, 30, 99, 0.95)',
'rgba(156, 39, 176, 0.9)',
'rgba(103, 58, 183, 0.85)',
'rgba(63, 81, 181, 0.8)',
'rgba(33, 150, 243, 0.75)',
'rgba(3, 169, 244, 0.7)',
'rgba(0, 188, 212, 0.7)',
'rgba(0, 150, 136, 0.75)',
'rgba(76, 175, 80, 0.8)',
'rgba(139, 195, 74, 0.85)',
'rgba(205, 220, 57, 0.9)',
'rgba(255, 235, 59, 0.95)',
'rgba(255, 193, 7, 1)'
],
components: {
// Main components
preview: true,
opacity: true,
hue: true,
// Input / output Options
interaction: {
hex: false,
rgba: false,
hsla: false,
hsva: true,
cmyk: false,
input: true,
clear: true,
save: true
}
}
});
}
render(){
return(
<Fragment>
<div className="color-picker"></div>
</Fragment>
)
}
}
you need to use events. For example:
pickr.on('save', (color, instance) => {
console.log('save', color, instance)
});

Add DataSet Bar Chart - Chart.JS

I´m tryng to make a bar chart in chart.js (using chart.js 2.2.2)
I´m in trouble trying to put new datasets in a chart
How can i put a new Dataset "Vendas" with data: [10,20,30,40,50,60,70]
var data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "Compras",
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1,
data: [65, 59, 80, 81, 56, 55, 40],
}
]
};
var ctx = $("#barOrgaoAno").get(0).getContext("2d");
var myBarChart = new Chart(ctx,{
type: "bar",
data: data,
});
I tried two examples i got in the internet but i can´t get neither to work
Exemple 1
barChartDemo.addData([dData()], "dD " + index);
Exemple2
JSFLiddle
var myNewDataset = {
label: "My Second dataset",
fillColor: "rgba(187,205,151,0.5)",
strokeColor: "rgba(187,205,151,0.8)",
highlightFill: "rgba(187,205,151,0.75)",
highlightStroke: "rgba(187,205,151,1)",
data: [48, 40, 19, 86, 27, 90, 28]
}
var bars = []
myNewDataset.data.forEach(function (value, i) {
bars.push(new myBarChart.BarClass({
value: value,
label: myBarChart.datasets[0].bars[i].label,
x: myBarChart.scale.calculateBarX(myBarChart.datasets.length + 1, myBarChart.datasets.length, i),
y: myBarChart.scale.endPoint,
width: myBarChart.scale.calculateBarWidth(myBarChart.datasets.length + 1),
base: myBarChart.scale.endPoint,
strokeColor: myNewDataset.strokeColor,
fillColor: myNewDataset.fillColor
}))
})
myBarChart.datasets.push({
bars: bars
})
myBarChart.update();
Since you store your chart data in a variable (called data in your code), you can do it with a simple function on a button :
$('button').click(function() {
// You create the new dataset `Vendas` with new data and color to differentiate
var newDataset = {
label: "Vendas",
backgroundColor: 'rgba(99, 255, 132, 0.2)',
borderColor: 'rgba(99, 255, 132, 1)',
borderWidth: 1,
data: [10, 20, 30, 40, 50, 60, 70],
}
// You add the newly created dataset to the list of `data`
data.datasets.push(newDataset);
// You update the chart to take into account the new dataset
myBarChart.update();
});
You can see the full code on this jsFiddle and here is its result after a click :
based on tektiv answer only, it didn't work for me.
I constructed the newDataSet just like he suggested, but I had a problem while pushing the Data.
to fix this, i had to do:
data.config.data.datasets.push(newDataSet);
instead of:
data.datasets.push(newDataSet);

Resources