How to add this GraphQL data to my pie chart in highcharts? - reactjs

I would appreciate any help that I can get with this
I need to plot a pie chart with 4 standard pies: ABC, BCD, CDE and DEF
Each Pie has a data point coming in from my GraphiQL resolver which looks like this:
{
"data": {
"metrics": {
"A": 56147.85,
"B": 116480.51,
"C": 56147.85,
"D": 120329.45000000001,
}
}
}
This is my highchart code for piechart
function PieChart() {
const { loading, error, data } = useQuery(CONC, {
variables: {
Currency: 'USD',
Date: {
date: '2019-05-01',
date_range: ['2019-05-01', '2019-06-10'],
},
Options: {
a: {
prop: '44',
csprop: ['14', '14', '40', '60'],
},
d: {
prop: '104',
csprop: ['511', '289', '519', '62'],
},
},
C: 'G',
Incl: false,
DFilters: [
{
by: 'P',
values: [],
},
],
},
});
const Top = [];
const First = [];
const Second = [];
const Rest = [];
data &&
data.metrics.forEach((e) => {
Top.push(e['A']);
First.push(e['B']);
Second.push(e['C']);
Rest.push(e['D']);
});
return (
<HighchartWrapper
chartOptions={{
chart: {
type: 'pie',
height: 230,
// width: 565,
},
title: {
text: '',
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>',
},
accessibility: {
point: {
valueSuffix: '%',
},
},
exporting: {
enabled: false,
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {point.percentage:.1f} %',
},
},
},
series: [
{
name: 'R',
data: [
{ name: 'ABC', y: Top},
{ name: 'BCD', y: First},
{ name: 'CDE', y: Second},
{ name: 'DEF', y: Rest},
],
},
],
}}
/>
);
}
export default memo(PieChart);
PROBLEM:
The GraphiQL query is generating results.
But I believe it's the way I am trying to push data that's giving me an empty pie chart
Thank you all in advance

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.

How Do you convert JQuery HighChart to React

Here is a full link to the project: Electoral Map
I have this Highchart map that I'm trying to convert to React but can't quite figure it out. I tried using React rappers but didn't succeed.
What I have:
JSON data - will be fetched from an API but I have hard-coded them as below.
Jquery functions that maps the data.
Several highcharts imports.
I have not included the path data, too long it wouldnt post.
$(function() {
var json = [{
"name": "Busia",
"registered": "251305",
"UDA": "0",
"Azimio": "0",
"value": "-5"
},{
"name": "Wajir",
"registered": "118091",
"UDA": "8",
"Azimio": "7",
"value": "-2"
}]
function init() {
function pointClick(json) {
var row = this.options.row,
$div = $('<div></div>')
.dialog({
title: ([this.name]),
width: 400,
height: 300
});
window.chart = new Highcharts.Chart({
chart: {
renderTo: $div[0],
type: 'pie',
width: 370,
height: 240
},
title: {
text: null
},
series: [{
name: 'Votes',
data: [{
name: 'Azimio',
color: '#0200D0',
y: Number(this.Azimio)
}, {
name: 'UDA',
color: '#C40401',
y: Number(this.UDA)
}],
dataLabels: {
format: '<b>{point.name}</b> {point.value:.1f}%'
}
}]
});
}
// Initiate the chart
$('#presidential').highcharts('Map', {
title: {
text: 'Presidential Electoral Map <em>(Kenya)</em>'
},
legend: {
title: {
text: 'Political Affiliation'
}
},
credits: {
enabled: false
},
tooltip: {
valueSuffix: 'Margin'
},
mapNavigation: {
enabled: true,
enableButtons: false
},
colorAxis: {
dataClasses: [{
from: 0.0000001,
to: 100,
color: '#C40401',
name: 'UDA'
}, {
from: -100,
to: -0.00000001,
color: '#0200D0',
name: 'Azimio'
}, {
from: 0,
to: 0,
color: '#C0C0C0',
name: 'Battle Ground(s)'
}]
},
series: [{
name: 'By County Difference',
point: {
events: {
click: pointClick
}
},
"type": "map",
"joinBy": ['name', 'name'],
"data": $.each(json, function() {}),
"mapData": [{
"name": "Busia",
"path": "M40,-534,43,-533,46,-532L46,-530L44,-528,44,-525C44,-525,41,-520,41,-520L40,-516,40,-513,41,-511C41,-511,44,-512,43,-509,43,-506,44,-504,44,-504L38,-499,38,-497,44,-495,45,-493,41,-489,41,-486L36,-486L34,-487,30,-488,28,-487,25,-484,22,-484,20,-486,18,-483,16,-481,15,-478,14,-476L14,-473L15,-471,14,-469L12,-469L10,-467,9,-464,10,-459C10,-459,9,-458,7,-457,5,-456,5,-455,5,-455L3,-459,0,-462,0,-465,2,-470,2,-474L2,-478L5,-481,8,-486,10,-491,13,-493L13,-495L12,-499,13,-503,15,-506,15,-510,16,-513C16,-513,19,-516,20,-517,21,-517,24,-519,24,-519L27,-519,28,-519,31,-520L31,-524L32,-526,33,-527,34,-531,35,-532z"
},
}]
}, {
"type": "mapline",
"data": [{
"name": "path5072",
"path": "M443,-449Z"
}]
}]
});
}
init()
});
I've reproduced your example in the working demo that you can find below.
What's important, I didn't use the dialog popup which is a specific jQuery method. Instead, I show a pie chart inside the tooltip, with the use of several point.events such like mouseOver, mouseOut and click as well.
point: {
events: {
//Show the default tooltip
mouseOver: function () {
let point = this;
this.series.chart.update({
tooltip: {
enabled: true,
formatter: function () {
let s = "";
s += `<span style="color:${point.color}">●</span> <span style="font-size: 10px"> ${point.series.name}</span><br/>`;
s += `${point.name}: ${point.value}<br/>`;
return s;
}
}
});
},
//Show the pie chart
click: function () {
let y1 = Number(this.Azimio);
let y2 = Number(this.UDA);
this.series.chart.update({
tooltip: {
useHTML: true,
enabled: true,
formatter: function () {
setTimeout(function () {
Highcharts.chart("chart", {
chart: {
type: "pie"
},
title: {
text: null
},
series: [
{
name: "Votes",
data: [
{
name: "Azimio",
color: "#0200D0",
y: y1
},
{
name: "UDA",
color: "#C40401",
y: y2
}
],
dataLabels: {
format: "<b>{point.name}</b> {point.value:.1f}%"
}
}
]
});
}, 10);
return '<div id="chart" style="width: 300px; height: 150px;"></div>';
}
}
});
},
//Remove the tooltip
mouseOut: function () {
this.series.chart.update({
tooltip: {
enabled: false
}
});
}
}
},
API REference:
https://api.highcharts.com/highmaps/series.map.point.events
Demo:
https://codesandbox.io/s/highcharts-react-demo-forked-44tmqt

How to update data on zoom in apexchart

I am trying to find a way in the apex chart. By which if user zoom on the year graph then the user should be able to get month data when they zoom on month data this should show the day data.
But I am not able to figure out if its possible in apex chart or not.
This is how my graph look like right now.
import React from "react";
import ReactApexChart from "react-apexcharts";
interface StackedGraphProps {}
type SeriesType = {
name: string;
data: number[];
};
interface StackedGraphState {
series: SeriesType[];
options: any;
}
class StackedBarGraph extends React.Component<
StackedGraphProps,
StackedGraphState
> {
constructor(props: any) {
super(props);
this.state = {
series: [
{
name: "Marine Sprite",
data: [44, 55, 41, 37, 22, 43, 21],
},
{
name: "Striking Calf",
data: [53, 32, 33, 52, 13, 43, 32],
},
{
name: "Tank Picture",
data: [12, 17, 11, 9, 15, 11, 20],
},
],
options: {
chart: {
events: {
zoomed: function (chartContext: any, { xaxis, yaxis }) {
console.log("xAxis", xaxis, yaxis);
},
selection: function (chartContext: any, { xaxis, yaxis }) {
console.log("Selecton", xaxis, yaxis);
},
dataPointSelection: (
event: any,
chartContext: any,
config: any
) => {
console.log("datapoint", chartContext, config);
},
},
zoom: {
enabled: true,
type: "x",
autoScaleYaxis: false,
// zoomedArea: {
// fill: {
// color: "#90CAF9",
// opacity: 0.4,
// },
// stroke: {
// color: "#0D47A1",
// opacity: 0.4,
// width: 1,
// },
// },
},
type: "bar",
height: 350,
stacked: true,
},
toolbar: {
show: true,
},
plotOptions: {
bar: {
horizontal: false,
},
},
stroke: {
width: 1,
colors: ["#fff"],
},
grid: {
row: {
colors: ["#fff", "#f2f2f2f2"],
},
},
title: {
text: "",
},
xaxis: {
tickPlacement: "on",
categories: [2008, 2009, 2010, 2011, 2012, 2013, 2014],
labels: {
formatter: function (val: any) {
return val + "K";
},
},
},
yaxis: {
title: {
text: undefined,
},
},
tooltip: {
y: {
formatter: function (val: any) {
return val + "K";
},
},
},
fill: {
opacity: 1,
},
legend: {
position: "top",
horizontalAlign: "left",
offsetX: 40,
},
},
};
}
render() {
return (
<div id="chart">
<ReactApexChart
zoomEnabled={true}
options={this.state.options}
series={this.state.series}
type="bar"
height={350}
/>
</div>
);
}
}
export default StackedBarGraph;

Issue with chartjs linear gradient for the mixed bar chart in ReactJS is not calculated for each individual Bars

Our requirement is to render the bar chart as Expected Image. we are using chartJs library to render the chart. we are able to render the bar chart but for one of the bar we need to show
the background color as gradient. To achieve this we used the following below code snippet:
but it render as Rendered graph. Can you please help me out in rendering the chart as expected.
JSFiddleLink
const data = [{
type: "Sample 1",
data: [600, 400, 200, 800]
}, {
type: "Sampel 2",
data: [700, 300, 600, 600]
}, {
type: "Total",
data: [1300, 700, 800, 1400]
}];
const gradient = document.getElementById('myChart').getContext('2d').createLinearGradient(0, 250, 0, 0);
gradient.addColorStop(1, '#acd7fa')
gradient.addColorStop(0.4, '#FFFFFF')
new Chart('myChart', {
type: "bar",
data: {
labels: ["A", "B", "C", "D"],
datasets: [
{
label: data[0].type,
xAxisID: "x1",
data: data[0].data,
// fillColor: background_1,
// highlightFill: background_2,
backgroundColor: "rgb(54, 162, 235)" ,
// backgroundColor: background_1,
barPercentage: 1,
},
{
label: data[1].type,
xAxisID: "x1",
data: data[1].data,
backgroundColor:"rgb(255, 159, 64)",
barPercentage: 1,
},
{
label: data[2].type,
xAxisID: "x2",
data: data[2].data,
backgroundColor: gradient,
barPercentage: 1,
},
],
},
options: {
legend: {
labels: {
filter: item => item.text != 'Total'
}
},
scales: {
yAxes: [{
ticks: {
min: 0,
stepSize: 200
}
}],
xAxes: [{
id: 'x1'
},
{
id: 'x2',
display: false,
offset: true
}
]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<canvas id="myChart" height="150"></canvas>
The Plugin Core API offers a range of hooks that may be used for performing custom code. You can use the afterLayout hook for creating different gradients for each value of the third dataset (the totals).
Please take a look at your amended code below and see how it works. You may also consult this StackBlitz that illustrates how it can be done with react-chartjs-2.
const data = [
{ type: "Sample 1", data: [600, 400, 200, 800] },
{ type: "Sampel 2", data: [700, 300, 600, 600] },
{ type: "Total", data: [1300, 700, 800, 1400] }
];
new Chart('myChart', {
type: "bar",
plugins: [{
afterLayout: chart => {
let ctx = chart.chart.ctx;
ctx.save();
let yAxis = chart.scales["y-axis-0"];
let yBottom = yAxis.getPixelForValue(0);
let dataset = chart.data.datasets[2];
dataset.backgroundColor = dataset.data.map(v => {
let yTop = yAxis.getPixelForValue(v);
let gradient = ctx.createLinearGradient(0, yBottom, 0, yTop);
gradient.addColorStop(0.4, '#FFFFFF');
gradient.addColorStop(1, '#acd7fa');
return gradient;
});
ctx.restore();
}
}],
data: {
labels: ["A", "B", "C", "D"],
datasets: [{
label: data[0].type,
xAxisID: "x1",
data: data[0].data,
backgroundColor: "rgb(54, 162, 235)",
barPercentage: 1
},
{
label: data[1].type,
xAxisID: "x1",
data: data[1].data,
backgroundColor: "rgb(255, 159, 64)",
barPercentage: 1
},
{
label: data[2].type,
xAxisID: "x2",
data: data[2].data,
barPercentage: 1
}
]
},
options: {
legend: {
labels: {
filter: item => item.text != 'Total'
}
},
scales: {
yAxes: [{
ticks: {
min: 0,
stepSize: 200
}
}],
xAxes: [{
id: 'x1'
},
{
id: 'x2',
display: false,
offset: true
}
]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<canvas id="myChart" height="150"></canvas>

How to plot a line and column chart in react-highstock?

I am trying to plot a line chart and a column chart on separate y-axes in highstock using react. However, the line chart is hidden behind the column chart. Could I have the line chart on the column chart as shown in their example dual chart - https://www.highcharts.com/demo/combo-dual-axes?
I've added a link to my chart to clarify my problem.
const chart_options= {
chart: {
zoomType: 'x'
},
title: {
text: ""
},
tooltip:{
split: false,
shared:true,
valueDecimals: 2
},
legend: {
enabled: true,
layout: 'horizontal'
},
series: [
{
name: 'ABC',
type: 'line',
data: this.props.data1,
yAxis:1,
color:'grey',
lineWidth: 3
},
{
name: 'DEF',
type: 'line',
data: this.props.data2,
yAxis:0,
},
{
name: 'GHI',
type: 'column',
data: this.props.data3,
yAxis:0,
color: '#ffd699',
dataGrouping:{
enabled: false
},
pointWidth: 1
},
],
xAxis: {
type: 'datetime',
gridLineWidth:1,
title: {
text: 'Time'
},
tickPixelInterval: 5
},
yAxis: [
{
labels: {
format: '{value:.0f}%',
},
opposite: false,
tickPixelInterval: 20
},
{
title: {
labels: {
format: '{value:.2f}',
},
tickPixelInterval: 20
},
],
}
Could someone please help?
Thanks.
You can set zIndex propert for the series:
series: [{
zIndex: 1,
...
}, {
zIndex: 0,
...
}]
Live demo: https://jsfiddle.net/BlackLabel/x5aefpLv/
API Reference: https://api.highcharts.com/highstock/series.column.zIndex

Resources