how to give string value on y axis in rechart - javascript

I am working on Recat.js and using rechart library for chart implementation. I want to give string value on the y axis as label and workout on some numbers included in the json data in x axis. here Iam giving my code I don't why its not working properly. the value key pair has to gone through x axis and label values on the y axis. but its not working . please help me to solve this issue. iam giving my code
"timestamp": 1645727400000,
"value": 1,
"label":"connection_recovered"
},
{
"timestamp": 1645790232297,
"value": 2,
"label":"up"
},
{
"timestamp": 1645790232297,
"value": -2,
"label":"down"
},
{
"timestamp": 1645790232297,
"value": 2,
"label":"up"
},
{
"timestamp": 1645790232297,
"value": -2,
"label":"down"
}]
return (
<Container lg={6}>
<ResponsiveContainer aspect="3">
<AreaChart
width={500}
height={400}
data={data}
margin={{
top: 10,
right: 30,
left: 0,
bottom: 0,
}}
>
<CartesianGrid strokeDasharray="3 3" />
<XAxis style={{fontSize:"12px"}} dataKey="timestamp" />
<YAxis dataKey="label" type="category" />
<Tooltip />
<defs>
<linearGradient id="splitColor" x1="0" y1="0" x2="0" y2="1">
<stop offset={off} stopColor="green" stopOpacity={1} />
<stop offset={off} stopColor="red" stopOpacity={1} />
</linearGradient>
</defs>
<Area style={{fontSize:"12px"}}
type="monotone"
dataKey="value"
stroke="#000"
fill="url(#splitColor)"
/>
</AreaChart>
</ResponsiveContainer>
</Container>
);
}

In your data array, I assumed that the values with
2 will always have the "up" label,
1 the "connection_recovered" label and
-2 the "down" label.
In order to have the label on a fixed tick in your graph on the YAxis, you can use the tickFormatter prop, where you can pass a function, which could return the label you want according to the value.
It would give the following:
// Depending on the value of the tick, you'll have a different label
function formatYAxis(value: number) {
switch(value) {
case 2:
return "up";
case -2:
return "down";
case 1:
return "connection_recovered";
default:
return ""
}
}
Used in the YAxis just like so:
<YAxis tickFormatter={formatYAxis} />
Which would give out a graph like the following

Related

Interval not working in recharts with day time series

I've some measurement values collecting over the day and I want to display them with a recharts bar graph between 00:00 - 23:59 for the whole day. I want to have 5 intervals in my chart: 00:00, 06:00, 12:00, 18:00 and 23:59. The sample data:
const data = {
events: [
{
time: 1674914690,
magnitude: 10
},
{
time: 1674916697,
magnitude: 20
},
{
time: 1674918713,
magnitude: 30
}
],
startTime: 1674860400,
endTime: 1674946799
};
The interval is not working or let's say recharts is doing some strange interval based on the data given and the intervals shown are not equal the number I give.
<BarChart
width={500}
height={500}
data={data.events}
margin={{ top: 5, right: 20, left: 10, bottom: 5 }}
>
<CartesianGrid stroke="#f5f5f5" />
<Bar
type="monotone"
dataKey="magnitude"
stroke="#ff7300"
dot={false}
barSize={2}
/>
<XAxis
type="number"
dataKey="time"
tickCount={5}
interval={"preserveStartEnd"}
tickFormatter={(timeStr) => timeFormatter(timeStr)}
domain={[data.startTime, data.endTime]}
/>
<YAxis />
</BarChart>
CodeBox
Is it possible in rechart to show these intervals?
From what I understand your problem is in the values ​​of StartTime and endTime, both are 4 hours behind what you want.
Substitute the code below in your timeFormatter function and see what happens.
var date = new Date((timestamp * 1000) + 14400000);
NOTE: This is not the solution to your problem.

Error in the values of the Rechart Stacked chart

I'm trying to build a Stacked Bar Chart using the Pchart library. I attach the code below.
function StackedBarChart({...props}){
const {dataChart:{data,keys}} = props;
const renderBars = () =>{
return keys.map((item,index)=>(
<Bar
key={index}
dataKey={item}
stackId='a'
fill={index%2?'blue':'red'}
label
/>
))
}
return(
<ResponsiveContainer width='100%' height={400}>
<BarChart
data={data}
stackOffset='expand'
>
<XAxis dataKey="name" />
<YAxis />
{renderBars()}
</BarChart>
</ResponsiveContainer>
)
}
When I output a value to each Bar I get incorrect signatures. . Why is 2 Bar subscribed with the value 1 and not the remaining percentage. What is my mistake ?
my data
const dataChart = {
data: [{
name: 'Page A',
count: 4000,
price: 2400,
},
{
name: 'Page B',
count: 3000,
price: 1398,
},
{
name: 'Page C',
count: 2000,
price: 9800,
},
],
keys: ['price', 'count']
};
The reason of this behavior, is that upper bar shown his top value, which is 1, so this is the sum of all bars stacked.
To avoid this situation I used valueAccessor and some formatting to get value of bar and count its percentage.
Here is a link to working codesandbox where you can see final result

How to understand "useBox" in react-three-fiber

I'm interested in learning how to create dynamic objects and group them together entirely in react/JavaScript. I'm looking at the chair and table in this example as my model:
https://codesandbox.io/s/ragdoll-physics-forked-bntr9
At this point, I'm not as concerned about the "physics" but just how to create the three object such as a table that consist of 5 3D-Rectangles.
I downloaded the above example, and this is the code for the table:
function Table() {
const [seat] = useBox(() => ({ type: 'Static', position: [9, -0.8, 0], args: [2.5, 0.25, 2.5] }))
const [leg1] = useBox(() => ({ type: 'Static', position: [7.2, -3, 1.8], args: [0.25, 2, 0.25] }))
const [leg2] = useBox(() => ({ type: 'Static', position: [10.8, -3, 1.8], args: [0.25, 2, 0.25] }))
const [leg3] = useBox(() => ({ type: 'Static', position: [7.2, -3, -1.8], args: [0.25, 2, 0.25] }))
const [leg4] = useBox(() => ({ type: 'Static', position: [10.8, -3, -1.8], args: [0.25, 2, 0.25] }))
return (
<>
<Box scale={[5, 0.5, 5]} ref={seat} />
<Box scale={[0.5, 4, 0.5]} ref={leg1} />
<Box scale={[0.5, 4, 0.5]} ref={leg2} />
<Box scale={[0.5, 4, 0.5]} ref={leg3} />
<Box scale={[0.5, 4, 0.5]} ref={leg4} />
<Suspense fallback={null}>
<Mug />
</Suspense>
</>
)
}
And at the top of the program I see this:
import {
Physics,
useBox,
useCompoundBody,
useCylinder,
useSphere,
usePlane,
useConeTwistConstraint,
usePointToPointConstraint
} from '#react-three/cannon'
Googling react-three/cannon took me to https://opensourcelibs.com/lib/use-cannon, and the "github" link took me to https://github.com/pmndrs/use-cannon, which I downloaded.
Is there a document to the "useBox", or do I have just have to read code to figure out how it works?
Without some doc, I can only do controlled variations, for example, suppose I just want to make the table legs longer, or the table top bigger? I don't understand what joins the legs to the table, but I figure it must be the position or args:
I tried changing 1.8 to 2.8 as follows:
from
const [leg1] = useBox(() => ({ type: 'Static', position: [7.2, -3, 1.8], args: [0.25, 2, 0.25] }))
to
const [leg1] = useBox(() => ({ type: 'Static', position: [7.2, -3, 2.8], args: [0.25, 2, 0.25] }))
and I could see the leg come out from the table top.
I knew all table legs had equal length, so I tried changing some number that was the same for all four legs (then later noticed two had 1.l8 and two had -1.8).
I'm also guessing that some set of three parameters must be length, width, height.
Then I tried changing:
<Box scale={[0.5, 4, 0.5]} ref={leg1} />
<Box scale={[0.5, 4, 0.5]} ref={leg2} />
to
<Box scale={[0.5, 6, 0.5]} ref={leg1} />
<Box scale={[0.5, 6, 0.5]} ref={leg2} />
And that deed indeed length two legs, but up through the top of the table.
So bottom line question is not how to do change the length of the legs, but how to find the documentation.
I searched the pmndrs library for "useBox", and see a many many matches:
I looked at the sources\hooks.ts and found this, which doesn't help me at all:
export function useBox(fn: GetByIndex<BoxProps>, fwdRef: Ref<Object3D> = null, deps?: DependencyList) {
const defaultBoxArgs: Triplet = [1, 1, 1]
return useBody('Box', fn, (args = defaultBoxArgs): Triplet => args, fwdRef, deps)
}
At this point, I'm not as concerned about the "physics" but just how
to create the three object such as a table that consist of 5
3D-Rectangles.
useBox is physics-only, it comes from the physics library "cannon", not from threejs or r3f. it approximates a shape and links it to arbitrary geometry. the physics engine now manages a literal box, a cube, and subjects it to gravity and other colliders. if your shape resembles something like a sphere you'd use useSphere instead and so on.
the example you have picked to learn either threejs or r3f is a hard one, i would not start with physics. the example on the github main page (https://codesandbox.io/s/rrppl0y8l4?file=/src/App.js) covers some basics, combine this with threejs docs at hand and you will have a much more comfortable learning experience.
a box in threejs (in react notation) is no more than this:
<mesh position={[1, 2, 3]} rotation={[Math.PI / 3, 0, 0]}>
<boxGeometry />
<meshBasicMaterial color="red" />
</mesh>
and you form groups like so:
<group>
<mesh>
..
if you want to start with physics later, here are some easier ones:
falling cubes: https://codesandbox.io/s/simple-physics-demo-z8e6m
christmas baubles: https://codesandbox.io/s/bestservedbold-christmas-baubles-zxpv7
arkanoid: https://codesandbox.io/s/arkanoid-under-60-loc-66cd7

display a photo in a list item undefined is not an object

I have a list of products, displayed using List Item from react-native-elements.
I want to add the product image as an 'icon' on the left of the product name.
I am having difficulty with an
'undefined is not an object'
when I call up the image.
I don't understand why an error is displayed, my array looks like this:
Object {
"cost": 1099.99,
"created_at": "2018-05-17T20:58:31Z",
"custom_fields": Array [],
"description": "",
"family_id": 5,
"id": 5,
"incl_tax": 1,
"is_visible": 1,
"name": "Apple MacBook Air 13.3'' LED 128 Go SSD 8 Go",
"photo": Object {
"_1_": Object {
"id": 1,
"order": 1,
"title_fr": "Apple-MacBook-Air-13-3-LED-128-Go-D-8-Go-RAM-Intel-Core-i5-bicoeur-a-1-8-Ghz-MQD32FN-Nouveau",
"url": "/i/p-4-6-5-146_5844_5_1.jpg",
},
},
"quantity": "0",
"reference": "",
"stock_status": "0",
"tax_rate_id": 1,
"unit": "",
"updated_at": "2018-06-27T10:43:46Z",
"weight": 0, },
So I call my photo like this:
<Image source={{uri:URL+ item.photo.1.url}} style={{ width: 25, height: 25}}/>
the constant 'URL' allows me to have the beginning of the url to which to add the end of the url of my array.
Seemed correct to me, I don't understand the error, do you see where the problem is? I will really need to figure out and fix this problem.
Thanks for anyone who will take the time to read my post and help me.
The code of this part :
<ListItem
style={{width:'100%'}}
containerStyle= {{backgroundColor: item % 2 === 0 ? '#000' : '#ccc'}}
bottomDivider
onPress={() => this.props.navigation.navigate('ProductDetails', {productId:parseInt(item.id)})}>
<ListItem.Content style={{flexDirection: 'row', justifyContent: 'space-between'}}>
<Image source={{uri:URL+ item.photo._1_.url}}
style={{ width: 25, height: 25}}/>
<ListItem.Title style={{width: '65%', fontSize: 16}}>{ ( item.name.length > 20 ) ? item.name.substring(0, 20) + ' ...' : item.name}</ListItem.Title>
<ListItem.Subtitle style={{ color: '#F78400', position: "absolute", bottom: 0, right: 0 }}>{item.cost}€</ListItem.Subtitle>
</ListItem.Content>
</ListItem>
Check this out
<Image source={URL+ item.photo["_1_"].url} style={{ width: 25, height: 25}}/>

Recharts Tooltip displays same value

I have an issue where the tooltip is displaying the same value for different series. So whenever I hover on the popover, I get the following:
Here's my implementation:
<LineChart margin={{ top: 15, right: 5, bottom: 5, left: 10 }}>
<XAxis
type='number'
dataKey='timestamp'
padding={{ left: 30, right: 30 }}
domain={['dataMin', 'dataMax']}
height={90}
tickFormatter={(unixTime) => dayjs(unixTime).format('MM/DD h:mm A')}
tickMargin={30}
/>
<YAxis
dataKey='Demand'
tickFormatter={(val, _axis) => numeral(val).format('0,0') + ' kW'}
/>
{chartData && this.renderLines(chartData, theme)}
<CartesianGrid strokeDasharray='3 3' />
<Legend />
<Tooltip
content={<LiveDailyDemandTooltip
format={{
Demand: '0.0'
}} />}
/>
</LineChart>
Where the data looks like:
{
"dataID-1": [
{Demand: 4237, timestamp: 1564977600000}
...
],
"dataID-2": [
{Demand: 112, timestamp: 1564977600000}
...
]
}
As mentioned here: https://github.com/recharts/recharts/issues/1625
You should set allowDuplicatedCategory to false in XAxis:
<XAxis allowDuplicatedCategory={false}/>
This will resolve the problem of duplicate value in tooltip.
I was able to resolve this by providing the data in a different format. It seems that Recharts needs to have data grouped by their X-Axis value:
[
{ timestamp: 1564977600000, Demand1: 4237, Demand2: 112 },
...
]

Categories

Resources