React Recharts data with array - reactjs

I have an array of data with the following structure:
0:
date: '01-12-2020',
data: Array(2)
{name: "plants", count: 5}
{name: "water", count: 2}
1:
date: '02-12-2020',
data: Array(2)
{name: "plants", count: 1}
{name: "water", count: 4}
...
I would like to show the dates on the x-axis and render a line for each `name' category. In this case two lines, one for plants and one for water.
Should I format this code or can I use this array directly in recharts? I'm creating the array myself in the backend so I can also format it there.
I've tried something like this but it is not working:
<ResponsiveContainer width="100%" height={200}>
<LineChart data={data}>
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="x" />
<YAxis />
<Tooltip />
{data.map((item, i) => (
<Line
dataKey={data[0].data[0].count}
type="monotone"
stroke={colors[0]}
activeDot={{ r: 8 }}
/>
))}
</LineChart>
</ResponsiveContainer>

Your data needs to be formatted into this :
[{name: '01-12-2020',
plants: 5
water : 4}]
you can do as following :
let result = [];
data.map(entry) => {
let obj = {date: entry.date}
entry.data.map((entry1) => {
obj[entry1.name] = entry1.count;
});
result.push(obj)
})
and your chart as following (your dataKey on XAxis is false)
<ChartContainer>
<ResponsiveContainer>
<LineChart
width={500}
height={300}
style={{ color: scoopBlue }}
data={data}
margin={{
top: 5,
right: 30,
left: 20,
bottom: 5
}}
>
<CartesianGrid strokeDasharray="3 3" />
<Legend />
<Line
type="monotone"
dataKey="plants"
stroke={scoopBlue}
strokeWidth={2}
activeDot={{ r: 5 }}
/>
<Line
type="monotone"
dataKey="water"
stroke={"orange"}
strokeWidth={2}
activeDot={{ r: 5 }}
/>
</LineChart>
</ResponsiveContainer>
</ChartContainer>

Related

How to sort values in Rechart on x-axis in ascending order

I've 3 demo datasets to visualize in React using Recharts.js.
{ x: 80, y: 50, name: "Page A" },
{ x: 14, y: 80, name: "Page B" },
{ x: 70, y: 38, name: "Page C" },
Unfortunately, the values on the x-axis are not ordered correctly (80 -> 14 -> 70), but follow the order of objects in the data array.
const rechart = () => {
return (
<div>
<ScatterChart width={400} height={400} data={data}>
<XAxis dataKey="x" domain={[0, 100]} />
<YAxis dataKey="y" domain={[0, 100]} axisLine={false} tick={false} />
<Scatter data={data}>
<LabelList dataKey="name" position="right" />
</Scatter>
</ScatterChart>
</div>
);
};
What can I do to sort the values from 0 to 100, not Page A to Page C?
Try sorting your data before passing it as props to the Scatter component
data.sort((a,b) => a.x - b.x)
const rechart = () => {
const sortedData = data.sort((a,b) => a.x - b.x)
return (
<div>
<ScatterChart width={400} height={400} data={data}>
<XAxis dataKey="x" domain={[0, 100]} />
<YAxis dataKey="y" domain={[0, 100]} axisLine={false} tick={false} />
<Scatter data={sortedData}>
<LabelList dataKey="name" position="right" />
</Scatter>
</ScatterChart>
</div>
);
};

Position timestamp between two ticks on X-axis

I have been trying to display data from server on multiple y axes scatter chart. I am receiving it filtered for the past 24 hours, but I am struggling to display it properly because for example single item is created in 23:01 and I need to position it between ticks 23 and 00 on the X-axis.
The following code is example for the past 4 hours, because on this sensor I still don't have data recorded for the past 24 hours:
The code I have created
<ResponsiveContainer width="100%" height="100%">
<ScatterChart
width={500}
height={400}
margin={{
top: 10,
right: 10,
bottom: 10,
left: 20,
}}
>
<CartesianGrid />
<XAxis
dataKey='created'
domain={['auto', 'auto']}
name='created'
tickFormatter={(unixTime) => moment(unixTime).format('HH')}
type='number'
/>
<YAxis yAxisId="left" type="number" dataKey="humidity" name="humidity" unit="%" stroke="#8884d8" />
<YAxis
yAxisId="right"
type="number"
dataKey="temperature"
name="temperature"
unit="°"
orientation="right"
stroke="#82ca9d"
/>
<Tooltip
cursor={{ strokeDasharray: '3 3', }}
formatter={(value: any, name: any, props: any) => {
if (name === 'created') {
return moment(value).format('HH:mm');
} else {
return value;
}
}}
/>
<Scatter yAxisId="left" name="A school" data={data} fill="#8884d8" />
<Scatter yAxisId="right" name="A school" data={data} fill="#82ca9d" />
</ScatterChart>
</ResponsiveContainer>
The data is coming in array of objects:
[
{
created: 1631199180006,
humidity: 9,
idStation: 3,
name: "Sofia"
status: "active"
temperature: 27
}
]
My question is how configure the ticks of the X-Axis to be positioned properly. I have read several posts and in my opinion I should create custom ticks but would be very grateful if someone gives ideas

Recharts set Y-axis to YES and NO

What code changes would I need to make to replace 1 with YES and 0 with NO?
It seems like it should be possible from the examples on http://recharts.org/ or just finding it from a general search, however I haven't found anything that resolves this.
The only part of the code that is I didn't post here are the imports at the top of the file.
Here is the graph
const data = [
{yl: "YES",name: "p1",'X axis': 1,},
{yl: "YES",name: "p2",'X axis': 1,},
{yl: "NO" ,name: "p3",'X axis': 0,},
];
export const esChart: React.FC = () => {
return (
<LineChart
width={500}
height={300}
data={data}
margin={{
top: 100,
right: 30,
left: 20,
bottom: 5
}}
>
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="name" />
<YAxis tickCount={1} />
<Tooltip />
<Legend />
<Line
type="monotone"
dataKey='X axis'
stroke="#8884d8"
activeDot={{ r: 8 }}
/>
</LineChart>
);
}
export default esChart;
You need to add tickFormatter prop to customize the same. (Working codesandbox)
<YAxis tickCount={1} tickFormatter={(...allArgs)=>{ console.log(allArgs) if(allArgs[0] ===0){ return "Y" }else{ return "N" } }}/>

Recharts grouping x-axis Labels

I have a requirement where I need to show the values between 1,2 as a group and 2,3 as a seperate group. I am trying to customise the x-axis but it's not working
In the above picture I need to show the bars 3 and 3.5 together with miminum gap between them and in sameway 4 and 4.5 together
and this is my code
<ResponsiveContainer width="100%" height="100%">
<ComposedChart
width={500}
height={400}
data={data}
>
<CartesianGrid horizontal={false} strokeDasharray="4 4" />
<XAxis scale="point" dataKey="label" />
<YAxis label={{ value: 'No.Of Employees', angle: -90, position: 'insideLeft' }} tick={false} />
<Tooltip />
<Bar dataKey="count" barSize={40} fill="#AAE5F9" />
<Line connectNulls={true} strokeWidth={3} dot={false} type="monotone" dataKey="count" stroke="#3080ED" />
</ComposedChart>
</ResponsiveContainer>
Any help would be thankfull
I assume your data looks like this:
const data = [
{label: "0", count: 0},
{label: "1", count: null},
{label: "2", count: 1},
{label: "3", count: 1},
{label: "3.5", count: 1},
{label: "4", count: 2},
{label: "4.5", count: 1},
{label: "5", count: 0},
];
They must be converted to the following form:
const data = [
{label: "0", countA: 0, countB: null},
{label: "1", countA: null, countB: null},
{label: "2", countA: 1, countB: null},
{label: "3-3.5", countA: 1, countB: 1},
{label: "4-4.5", countA: 2, countB: 1},
{label: "5", countA: 0, countB: 0},
];
The first method
Add another Bar component to display values in group.
export default function App() {
return (
// <ResponsiveContainer width="100%" height="100%">
<ComposedChart
width={500}
height={400}
data={data}
>
<CartesianGrid horizontal={false} strokeDasharray="4 4" />
<XAxis scale="point" dataKey="label" />
<YAxis label={{ value: 'No.Of Employees', angle: -90, position: 'insideLeft' }} tick={false} />
<Tooltip />
<Bar dataKey="countA" barSize={20} fill="#AAE5F9" />
<Bar dataKey="countB" barSize={20} fill="#79B473" />
<Line connectNulls={true} strokeWidth={3} dot={false} type="monotone" dataKey="countA" stroke="#3080ED" />
</ComposedChart>
// </ResponsiveContainer>
);
}
Result:
The second method
If you want the columns in the groups to be the same width regardless of how many elements are in the group, then you can draw the rectangle for the group yourself.
const getPath = (x, y, width, height, uv, pv) => {
const height1= pv?(height/uv)*pv:height;
return `M${x},${y}
v${height}
h${width}
v${-height1}
h${-width/2}
v${(height1-height)}
h${-width/2}
Z`;
};
const MultiBar: FunctionComponent = (props) => {
const { fill, x, y, width, height, countA, countB } = props;
return <path d={getPath(x, y, width, height, countA, countB)} stroke="none" fill={fill} />;
};
export default function App() {
return (
<ComposedChart
width={500}
height={400}
data={data}
>
<CartesianGrid horizontal={false} strokeDasharray="4 4" />
<XAxis dataKey="label" />
<YAxis type="number" domain={[0, 2]} label={{ value: 'No.Of Employees', angle: -90, position: 'insideLeft' }} tick={false} />
<Bar
dataKey="countA"
fill="#AAE5F9"
shape={<MultiBar />}
>
</Bar>
<Line connectNulls={true} strokeWidth={3} dot={false} type="monotone" dataKey="countA" stroke="#3080ED" />
</ComposedChart>
);
}
Result:
The getPath function returns the path of the SVG element for drawing each bar of the chart. If required, you can add a stroke or make a gap between the bars in the group.
Also, you need to set the domain for the Y-axis by the maximum value of all countA and countB values:
<YAxis type="number" domain={[0, 2]} ... />

How to change the label in recharts?

<BarChart
isAnimationActive={false}
width={400}
height={200}
data={value}
margin={{
top: 5, right: 30, left: 20,
}}
>
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="x"
/>
<YAxis label={{ value: `no.`, angle: -90, position: 'insideBottomLeft' }} />
<Tooltip
content={<CustomTooltip />}
/>
<Bar dataKey="y" /* fill={colors[0]} */ >
</BarChart>
My data on x axis is numerical [0,1,2,3...] but I want my ticks to be [A1,A2,A3...]
you can use formatter attribute, here is an example
<XAxis dataKey="x" tickFormatter={(t) => `A${t+1}`} />
Change your value key
const value = [
{
x: 'A1', ......
},
{
x: 'A2', .....
},
]
Or you can use this:
<XAxis
dataKey="x"
tickFormatter={(t) => {
const count = parseInt(t) + 1
return 'A'+ count;
}
}
/>

Resources