React bizchart add axis name - reactjs

Im using my react project for biz-chart , i have some conflict on the adding X and Y axis to name, anyone know how to added this correctly ?
here the image description
live sample code here
Thanks
code here
import React from "react";
import {
G2,
Chart,
Geom,
Axis,
Tooltip,
Coord,
Label,
Legend,
View,
Guide,
Shape,
Facet,
Util
} from "bizcharts#3.5.8";
import DataSet from "#antv/data-set";
class Groupedcolumn extends React.Component {
render() {
const data = [
{
name: "London",
"Jan.": 18.9,
"Feb.": 28.8,
"Mar.": 39.3,
"Apr.": 81.4,
May: 47,
"Jun.": 20.3,
"Jul.": 24,
"Aug.": 35.6
},
{
name: "Berlin",
"Jan.": 12.4,
"Feb.": 23.2,
"Mar.": 34.5,
"Apr.": 99.7,
May: 52.6,
"Jun.": 35.5,
"Jul.": 37.4,
"Aug.": 42.4
}
];
const ds = new DataSet();
const dv = ds.createView().source(data);
dv.transform({
type: "fold",
fields: ["Jan.", "Feb.", "Mar.", "Apr.", "May", "Jun.", "Jul.", "Aug."],
// 展开字段集
key: "月份",
// key字段
value: "月均降雨量" // value字段
});
return (
<div>
<Chart height={400} data={dv} forceFit>
<Axis name="月份" />
<Axis name="月均降雨量" />
<Legend />
<Tooltip
crosshairs={{
type: "y"
}}
/>
<Geom
type="interval"
position="月份*月均降雨量"
color={"name"}
adjust={[
{
type: "dodge",
marginRatio: 1 / 32
}
]}
/>
</Chart>
</div>
);
}
}

Can add a title to the Axis component
title={{
autoRotate: true, // 是否需要自动旋转,默认为 true
offset: 40, // 设置标题 title 距离坐标轴线的距离
textStyle: {
fontSize: '12',
textAlign: 'center',
fill: '#999',
fontWeight: 'bold',
},
position: 'center', // 标题的位置,**新增**
}}

Related

React react-chartjs-2 adding x and y axis labels to a line graph

import React from "react";
import { Line } from "react-chartjs-2";
// "chart.js": "^2.9.4",
// "react-chartjs-2": "^2.11.1"
const ext_data = [11, 19, 3, 5, 2, 3, 14, 19];
const ll = Array.from(Array(ext_data.length).keys());
const data = {
labels: ll,
datasets: [
{
label: "Profit$",
data: ext_data,
fill: false,
backgroundColor: "rgb(255, 99, 132)",
borderColor: "rgba(255, 99, 132, 0.4)"
}
]
};
const options = {
scales: {
yAxes: [
{
ticks: {
beginAtZero: true
}
}
]
}
};
const LineChart = () => (
<>
<div className="header">
<h1 className="title">Profit Trend</h1>
<div className="links"></div>
</div>
<Line data={data} options={options} />
</>
);
export default LineChart;
I am trying to add x-axis name : "time" and y-axis name: "number of cars".
I went into the documentation : https://www.chartjs.org/docs/latest/axes/labelling.html
However, I was not able to find something that was useful.
Thank you for your time.
In react-chartjs-2, to add your title to your axis, just add this to your yAxes array of options (options.scales.yAxes[]):
scaleLabel: {
display: true,
labelString: "number of cars",
fontColor: "color you want",
}
same for your xAxes.

react-chartjs-2 options are not recognized for Bars

I am trying to built a barchart component via "react-chartjs-2". I did pretty much paste my code from here: https://www.c-sharpcorner.com/article/create-different-charts-in-react-using-chart-js-library/.
This is how it looks:
import React from 'react';
import {Bar} from "react-chartjs-2";
const BarChart = () => {
const barChartData = {
labels: ["October", "November", "December"],
datasets: [
{
data: [8137119, 9431691, 10266674],
label: "Infected People",
borderColor: "#3333ff",
backgroundColor: "#547db4",
fill: true
},
{
data: [1216410, 1371390, 1477380],
label: "Deaths People",
borderColor: "#ff3333",
backgroundColor: "#f7813e",
fill: true
}
]
};
const barChart = (
<Bar
type="bar"
width={130}
height={50}
options={{
title: {
display: true,
text: "COVID-19 Cases of Last 3 Months",
fontSize: 15
},
legend: {
display: true, //Is the legend shown?
position: "bottom" //Position of the legend.
}
}}
data={barChartData}
/>
);
return barChart;
};
export default BarChart
Everything seems to be working fine, besides the fact that the options prop is not being recognized by the code.
Did anyone come across a similar issue and can help me out?
Update options prop as bellow.
options = {{
plugins: {
title: {
display: true,
text: "COVID-19 Cases of Last 3 Months"
},
legend: {
display: true,
position: "bottom"
}
}
}}

How to show data value on top of bar in react-chartjs-2?

I made bar chart in react-chartjs-2. I want to show data value of each bar on the top of the bar. For that I used the plugin calls chartjs-plugin-datalabels But it's not showing anything.
is it possible to show each value of bar chart ?
I want to show data value somethings like this.
Here is my code.
import React, { Component } from "react";
import "chartjs-plugin-datalabels";
import { Bar } from "react-chartjs-2";
export default class Button extends Component {
render() {
const dataBar = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "My First dataset",
backgroundColor: "#EC932F",
borderColor: "rgba(255,99,132,1)",
borderWidth: 1,
hoverBackgroundColor: "rgba(255,99,132,0.4)",
hoverBorderColor: "rgba(255,99,132,1)",
data: [65, 59, 80, 81, 56, 55, 40]
}
]
};
const options = {
plugins: {
datalabels: {
display: true,
color: "black"
}
},
legend: {
display: false
}
};
return (
<div>
<Bar data={dataBar} options={options} width={100} height={50} />
</div>
);
}
}
Any help would be appreciated.
import React, { Component } from "react";
import Chart from "chart.js/auto";
import ChartDataLabels from "chartjs-plugin-datalabels";
import { Bar } from "react-chartjs-2";
export default class Button extends Component {
componentDidMount() {
Chart.register(ChartDataLabels);
}
render() {
const dataBar = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "My First dataset",
backgroundColor: "#EC932F",
borderColor: "rgba(255,99,132,1)",
borderWidth: 1,
hoverBackgroundColor: "rgba(255,99,132,0.4)",
hoverBorderColor: "rgba(255,99,132,1)",
data: [65, 59, 80, 81, 56, 55, 40]
}
]
};
const options = {
plugins: {
datalabels: {
display: true,
color: "black",
formatter: Math.round,
anchor: "end",
offset: -20,
align: "start"
}
},
legend: {
display: false
}
};
return (
<div>
<Bar data={dataBar} options={options} width={100} height={50} />
</div>
);
}
}
Here you can see in componentDidMount we have registered chart data label plugin for displaying data.
And another thing is in the options added few more parameters as per below field
anchor: "end",
offset: -20,
align: "start"
This is used for displaying data in the top.
The react-chartjs-2 package holds a plugin property which can be set on the components.
Change the import from:
import "chartjs-plugin-datalabels";
to:
import ChartDataLabels from 'chartjs-plugin-datalabels';
On your component, add the plugin variable which holds the imported value.
from:
<Line data={data} options={options} />
to:
<Line data={data} plugins={[ChartDataLabels]} options={options} />
See this original stackoverflow answer to the similar question
use this "chartjs-plugin-datalabels": "^0.5.0" version
it works for me
Here is working example
https://codesandbox.io/s/barchart-knycb
const options2 = {
plugins: {
datalabels: {
anchor: "end",
align: "start",
formatter:(value,context)=>{
const datasetArray = []
context.chart.data.datasets.forEach((dataset)=>{
if(dataset.data[context.dataIndex] != undefined){
datasetArray.push(dataset.data[context.dataIndex])
}
})
function totalSum(total, datapoint){
return total + datapoint;
}
let sum = datasetArray.reduce(totalSum,0)
if(context.datasetIndex == datasetArray.length-1)
return sum
else
return ''
},
},
title: {
display: true,
text: 'Chart.js Bar Chart - Stacked',
},
},
responsive: true,
scales: {
x: {
stacked: true,
ticks: {
maxRotation: 70,
minRotation: 70
}
},
y: {
stacked: true,
},
},
};
const data1 = {
labels,
datasets: [
{
label: 'Dataset One',
data: [1,2,3,4,5,6,7],
backgroundColor: 'rgba(255, 99, 132, 0.5)',
},
{
label: 'Dataset Two',
data: [1,8,3,4,9,6,7],
backgroundColor: 'rgba(53, 162, 235, 0.5)',
},
],
};

How to display dynamic multiline graph using chart.js in reactjs

I want to display a multiline graph for plan1 and plan2 with age on x-axis and totalnestegg on y-axis.
I have 4 array objects with age1 for plan1, totalnestegg1 for plan1, age2 for plan2 and totalnestegg2 for plan2.
I am able to display single plan but not mulitline.
age1 has items like [65,70,71,......,100] with corresponding amounts in totalamount1.
age2 has items like [70,71,72,......,100] with corresponding amounts in totalamount1.
I do know how to display labels for this kind, my current code looks like shown below:
import React from 'react';
import {Line} from 'react-chartjs-2';
export default class DisplayGraph extends React.Component {
state = {
labels: [],
datasets: [
{
label: 'Plan 1',
fill: true,
lineTension: 0,
backgroundColor: 'gray',
borderColor: 'gray',
borderWidth: 0,
data: this.props.totalNestEggForGraph1
},
{
label: 'Plan 2',
fill: true,
lineTension: 0,
backgroundColor: '#ccccff',
borderColor: 'gray',
borderWidth: 0,
data: this.props.totalNestEggForGraph2
}
]
}
render() {
return (
<div>
<Line
data={this.state}
options={{
title:{
display:true,
text:'Size of Retirement Savings',
fontSize:20
},
legend:{
display:true,
position:'right'
}
}}
/>
</div>
);
}
}

breaking big component into smaller one

I'm working on separating code from index.tsx into two different files viz: firstTab.tsx and secondTab.tsx. I haven't started working on secondTab.tsx yet.
I separated first tab related code into firstTab.tsx as shown in the following code editor: The full functional code with both tabs working are in index.tsx is pasted below:
import React, { Component } from "react";
import { render } from "react-dom";
import "jqwidgets-scripts/jqwidgets/styles/jqx.base.css";
import JqxButton from "jqwidgets-scripts/jqwidgets-react-tsx/jqxbuttons";
import * as ReactDOM from "react-dom";
import JqxWindow from "jqwidgets-scripts/jqwidgets-react-tsx/jqxwindow";
import JqxInput from "jqwidgets-scripts/jqwidgets-react-tsx/jqxinput";
import JqxChart, {
IChartProps
} from "jqwidgets-scripts/jqwidgets-react-tsx/jqxchart";
import JqxGrid, {
IGridProps,
jqx
} from "jqwidgets-scripts/jqwidgets-react-tsx/jqxgrid";
import JqxTabs from "jqwidgets-scripts/jqwidgets-react-tsx/jqxtabs";
import JqxDropDownList, {
IDropDownListProps
} from "jqwidgets-scripts/jqwidgets-react-tsx/jqxdropdownlist";
import firstTab from './firstTab';
interface AppProps {}
interface AppState {
name: string;
}
interface IProps extends IGridProps {
dropdownlistSource: IDropDownListProps["source"];
}
class App extends Component<{}, IProps> {
private myTabs = React.createRef<JqxTabs>();
private gridElement = React.createRef<HTMLDivElement>();
private myGrid = React.createRef<JqxGrid>();
private gridElementTwo = React.createRef<HTMLDivElement>();
private myGrid2 = React.createRef<JqxGrid>();
constructor(props: {}) {
super(props);
this.state = {
dropdownlistSource: [
{ value: 0, label: "Affogato" },
{ value: 1, label: "Americano" },
{ value: 2, label: "Bicerin" },
{ value: 3, label: "Breve" }
]
};
}
public render() {
return (
<JqxTabs
ref={this.myTabs}
// #ts-ignore
width={400}
height={560}
initTabContent={this.initWidgets}
>
<ul>
<li style={{ marginLeft: 30 }}>
<div style={{ height: 20, marginTop: 5 }}>
<div
style={{
marginLeft: 4,
verticalAlign: "middle",
textAlign: "center",
float: "left"
}}
>
US Indexes
</div>
</div>
</li>
<li>
<div style={{ height: 20, marginTop: 5 }}>
<div
style={{
marginLeft: 4,
verticalAlign: "middle",
textAlign: "center",
float: "left"
}}
>
NASDAQ compared to S&P 500
</div>
</div>
</li>
</ul>
<div style={{ overflow: "hidden" }}>
<div id="jqxGrid" ref={this.gridElement} />
<div style={{ marginTop: 10, height: "15%" }} />
</div>
<div style={{ overflow: "hidden" }}>
<div id="jqxGrid2" ref={this.gridElementTwo} />
<div style={{ marginTop: 10, height: "15%" }} />
</div>
</JqxTabs>
);
}
private initGrid = () => {
const source = {
datafields: [{ name: "Date" }, { name: "S&P 500" }, { name: "NASDAQ" }],
datatype: "csv",
localdata: `1/2/2014,1831.98,4143.07
1/3/2014,1831.37,4131.91
1/6/2014,1826.77,4113.68
1/7/2014,1837.88,4153.18
1/8/2014,1837.49,4165.61
1/9/2014,1838.13,4156.19
2/6/2014,1773.43,4057.12
2/7/2014,1797.02,4125.86`
};
const dataAdapter = new jqx.dataAdapter(source, {
async: false,
loadError: (xhr: any, status: any, error: any) => {
console.log(xhr, status, error);
}
});
const columns: IGridProps["columns"] = [
{ cellsformat: "d", datafield: "Date", text: "Date", width: 250 },
{ datafield: "S&P 500", text: "S&P 500", width: 150 },
{ datafield: "NASDAQ", text: "NASDAQ" }
];
const grid = (
<JqxGrid
ref={this.myGrid}
width={"100%"}
height={400}
source={dataAdapter}
columns={columns}
/>
);
render(grid, this.gridElement.current!);
};
private initGrid2 = () => {
const source = {
datafields: [{ name: "Date" }, { name: "S&P 500" }, { name: "NASDAQ" }],
datatype: "csv",
localdata: `1/2/2014,1831.98,4143.07
1/3/2014,1831.37,4131.91
1/6/2014,1826.77,4113.68
1/7/2014,1837.88,4153.18
1/8/2014,1837.49,4165.61
1/9/2014,1838.13,4156.19
1/10/2014,1842.37,4174.67
2/7/2014,1797.02,4125.86`
};
const dataAdapter = new jqx.dataAdapter(source, {
async: false,
loadError: (xhr: any, status: any, error: any) => {
console.log(xhr, status, error);
}
});
const columns: IGridProps["columns"] = [
{ cellsformat: "d", datafield: "Date", text: "Date", width: 250 },
{ datafield: "S&P 500", text: "S&P 500", width: 150 },
{ datafield: "NASDAQ", text: "NASDAQ" }
];
const grid = (
<JqxGrid
ref={this.myGrid2}
width={"100%"}
height={400}
source={dataAdapter}
columns={columns}
/>
);
render(grid, this.gridElementTwo.current!);
};
private initWidgets = (tab: any) => {
switch (tab) {
case 0:
this.initGrid();
break;
case 1:
this.initGrid2();
break;
}
};
}
render(<App />, document.getElementById("root"));
Question:
Since I've already moved private initGrid = () => { inside a separate file firstTab.tsx, in index.tsx where should I put {firstTab.tsx} to make sure both tabs in index.tsx works fine? I mean, even if I comment out private initGrid = () => { function from index.tsx both tabs should work fine.
Thanks
If I would refactor this I would consider the next approach:
Create Parent component Table (probably some more appropriate name)
Create a component for US Indexes
Create a component for NASDAQ compared to S&P 500
Based on the active tab render the proper component.
You could also create a separate file that contains only exports with your data.
If you then import that into your files with the functions you can use that there, keeps it cleaner.
And if you pass that data as a prop / param to your initGrid() functions, you don't have to repeat that code, can reuse it.

Resources