FormidableLabs / victory-native-xl

A charting library for React Native with a focus on performance and customization.
https://commerce.nearform.com/open-source/victory-native
719 stars 53 forks source link

Plot two lines with different x and y values on the same chart #260

Open harshit-khandelwal-pi opened 6 months ago

harshit-khandelwal-pi commented 6 months ago

Question

Is there a way to plot two lines with different x and y values on the same chart?

Background Info/Attempts

const o1 = { x: [0, 2, 3, 5, 20], y: [10, 15, 20, 25, 30] }; const o2 = { x: [0, 3, 4, 6, 7], y: [5, 10, 15, 20, 25] };

I can keep the domain as [0,20]

I have these above two objects for which I want to plot two separate lines in the same chart. Is there a way I can do this?

jjojo commented 3 months ago

You should be able to do this but you need to transform your dat a bit. Something like this I guess: [{x:0, y0: 10, y1:5}, {x:1}, {x:2, y0: 10}, {x:3, y0:20, y1: 10}] and so on.

const o1 = { x: [0, 2, 3, 5, 20], y: [10, 15, 20, 25, 30] };
const o2 = { x: [0, 3, 4, 6, 7], y: [5, 10, 15, 20, 25] };

const mergeData = (o1, o2) => {
    // Create a set of all unique x values
    const allXValues = [...new Set([...o1.x, ...o2.x])].sort((a, b) => a - b);

    // Map x values to the desired output format
    return allXValues.map(x => {
        const obj = { x };

        const o1Index = o1.x.indexOf(x);
        const o2Index = o2.x.indexOf(x);

        if (o1Index !== -1) {
            obj.y0 = o1.y[o1Index];
        }
        if (o2Index !== -1) {
            obj.y1 = o2.y[o2Index];
        }

        return obj;
    });
};

const mergedData = mergeData(o1, o2);
console.log(mergedData);

/*
[
    { x: 0, y0: 10, y1: 5 },
    { x: 2, y0: 15 },
    { x: 3, y0: 20, y1: 10 },
    { x: 4, y1: 15 },
    { x: 5, y0: 25 },
    { x: 6, y1: 20 },
    { x: 7, y1: 25 },
    { x: 20, y0: 30 }
]
*/

And then you need to set xKey="x" and yKeys={["y0", "y1"]} on the <CartesianChart> component