How to prevent breaking axis long labels in React Recharts? - reactjs

I'am using React Recharts (http://recharts.org/en-US/) to show some chart data and I need to show formatted values nearby axis. Axis values is separated by spaces, for example 1 000 000 $. React Recharts is breaking values into separate lines
How to prevent breaking labels and show it fully at the same line?

Have you tried using a tick formatter? I tried to reproduce your problem but it couldn't.
Here is a re-purposed chart that is working just fine for me.
<ResponsiveContainer height={400} width="100%">
<ComposedChart
height={400}
width="100%"
margin={{ top: 20, right: 20, bottom: 20, left: 20 }}
>
<CartesianGrid />
<XAxis dataKey="name" />
<YAxis
unit="$"
dataKey="y"
tickFormatter={val => val.toLocaleString().replace(/,/g, " ")}
/>
<Scatter
name="A school"
data={[
{ name: "Jill", y: 3000000 },
{ name: "Eve", y: 5000000 },
{ name: "Audrey", y: 1000000 },
{ name: "Jaqueline", y: 7000000 }
]}
fill="#8884d8"
/>
<Tooltip />
</ComposedChart>
</ResponsiveContainer>
Let me know if misunderstood your question.

You can specify the width for tick
For example,
<YAxis tick={{ width: 75 }} tickFormatter={formatter} domain={yDomain} allowDataOverflow/>

Related

How to get Recharts to dynamically change color from a variable in data

I'm trying to add color to parts of a Rechart plot (based on a value in the data). The chart that I'm trying to recreate is shown below. Here is my code currently which just plots the chart with one color https://codesandbox.io/s/stupefied-shamir-e1u0vt?file=/src/App.js.
I tried using linearGradient in the way shown below (commented) but that seems to gives 2 colors (red if above a certain y value and green if below).
The data format:
>>> data = [{X: 100, Y: 200, Speed: 0},{X: 200, Y: 200, Speed: 1},{X: 300, Y: 400, Speed: 3}]
Current Recharts Code:
<LineChart
width={600}
height={300}
margin={{ top: 5, right: 30, left: 20, bottom: 5 }}
data={data}
>
{/* <defs>
<linearGradient id="colorSpeed" x1="0%" y1="0%" x2="0%" y2="100%">
<stop offset="0%" stopColor="red" />
<stop offset="100%" stopColor="green" />
</linearGradient>
</defs> */}
<Line dot={false} type="monotype" dataKey="Y"
// stroke="url(#colorSpeed)"
/>
<XAxis type="number" dataKey="X" domain={["auto", "auto"]} />
<YAxis domain={("auto", "auto")} />
<Tooltip />
<Legend />
</LineChart>
What I'm trying to recreate:

Uncaught TypeError: Cannot assign to read only property '0' of string 'Client' when using Recharts

I am trying to create a Stacked Bar from Recharts but I get the title error. The thing here is that locally in a separate React project is working properly but when I try to implement it in a legacy code is shows this error. Does it have any connection with the implementation or is there any obvious error in my code?
My data are:
Values: [
{ Other: 1000,
Client: 40,
period: "2021"
transactions: 10
},
{ Other: 4000,
Client: 10,
period: "2021"
transactions: 30
},
{ Other: 10500,
Client: 20,
period: "2021"
transactions: 40
}
]
And my component is like this:
<ComposedChart
data={mappedValues}
margin={{
top: 20,
right: 80,
bottom: 20,
left: 20,
}}
>
<CartesianGrid stroke="#EBF0FA" vertical={false} />
<XAxis
dataKey="periodFixed"
axisLine={false}
tickLine={false}
tick={<CustomizedAxisTick />}
/>
<YAxis
yAxisId="left"
axisLine={false}
tickLine={false}
tickFormatter={formatYAxis}
stroke="rgba(99, 110, 131, 0.5)"
/>
<YAxis
yAxisId="right"
orientation="right"
axisLine={false}
tickLine={false}
stroke="rgba(99, 110, 131, 0.5)"
/>
<Tooltip />
{legendFlag ? (
<Legend
wrapperStyle={{
paddingTop: "25px",
paddingLeft: "10px",
}}
/>
) : null}
/* the below part with the stacked bars is throwing the error */
<Bar dataKey="Client" stackId="a" fill="#23AC70" />
<Bar dataKey="Others" stackId="a" fill="#003972" />
<Line
type="linear"
yAxisId="right"
dataKey="transactions"
stroke="#ADD868"
dot={false}
/>
</ComposedChart>
Any idea what is happening?

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

how to show custom values on x-axis in recharts?

<LineChart
width={400}
height={200}
data={data}
margin={{
top: 5, right: 30, left: 20,
}}
>
<CartesianGrid />
<XAxis dataKey="x" /* tick={false} *//>
<YAxis />
<Tooltip content={tooltipContent}/>
<Line type="monotone" dataKey="y" strokeWidth={1} dot={false} activeDot={{ r: 5 }} />
</LineChart>
my dataset includes just the decimal points(23.444,54.6665,..). I want to divide the axis into equal 10 halves (10,20,30,...100). How can I show these values on axis?
below is the image of the chart
[1]: https://i.stack.imgur.com/TatGP.png
To use custom values on the XAxis, or custom ticks, you need to use the following props on your XAxis component:
Specify the type of the values to number with type="number"
Supply the tick values ticks={[10, 20, 30, [...], 100]}
And the domain to specify the limits domain={[10, 100]}
In the end, your XAxis should look like this:
<XAxis
dataKey="x"
type="number"
ticks={[10, 20, 30, [...], 100]}
domain={[10, 100]}
/>

Recharts: allowDuplicatedCategories breaks Tooltip

I have a chart that redraws lines based on React state filters. By default, the tooltip appears and works for all points on the line, but once I change the state by selecting a different filter, the tooltip no longer appears. Changing allowDuplicatedCatories={true} fixes the issue, but then the tooltip doesn't appear on all points since there are duplicate categories. Is there a workaround to keep this flag as false but show the tooltip on every line without completely restructuring the data format?
Relevant code: Note: dataKeys is an array of keys that are generated when the user selects a combination of filters.
<ComposedChart data={chartData}>
<XAxis
label={{
value: "Date",
position: "bottom",
dy: 10,
fontSize: 16,
}}
tickFormatter={(tick) => {
const parts = tick.split("-");
return `${this.tickLabels[parts[1]]}/${parts[2]}`;
}}
dy={10}
dataKey="date"
tick={{ fontSize: 12 }}
padding={{ left: 20, right: 20 }}
interval="preserveStartEnd"
allowDuplicatedCategory={false}
/>
<CartesianGrid stroke="#f5f5f5" />
<Tooltip
cursor={{ stroke: "#4c5b5f", strokeWidth: 1 }}
formatter={(value) => Math.round(value)}
/>
{dataKeys.map((key, i) => (
<Line
name={`${
(this.legendLabels[key] || key).split(`|`)[0]
}, ${key.split(`|`)[1]} (Mean)`}
type="monotone"
dataKey={`amt_${key}`}
connectNulls
dot={false}
/>
))}
</ComposedChart>

Resources