如何在Victory Native中自定义数据键替代默认x、y绘制图表
Got it, let's tackle how to use your custom data keys (myx for the x-axis and step for the y-axis) in Victory Native. Here's a straightforward solution:
First, quick note: Your target data has a typo in the 5th entry (myxx instead of myx)—I'll fix that in the example below to avoid rendering issues.
Step 1: Prepare Your Updated Data
Ensure your data uses the correct custom keys:
const sampleData = [ { key:'1',myx: 'Jan', step: 5.5, c0: 2,date:'18 Jan 2019',bank:'Bank Of India',txid:'76jhdg74rh4h848r58'}, { key:'2',myx: 'Feb',step: 3, c0: 1.5, date:'08 Feb 2019',bank:'Bank Of Baroda',txid:'76jhdg74rh4h848r58'}, { key:'3',myx: 'March', step: 5, c0: 2 ,date:'19 March 2019',bank:'State Bank of India',txid:'76jhdg74rh4h848r58'}, { key:'4',myx: 'Apr', step: 4, c0: 1 ,date:'18 Apr 2019',bank:'Bank Of India',txid:'76jhdg74rh4h848r58'}, { key:'5',myx: 'May', step: 6, c0: 2 ,date:'15 May 2019',bank:'Bank Of India',txid:'76jhdg74rh4h848r58'}, // Fixed typo from `myxx` to `myx` { key:'6',myx: 'June', step: 2, c0: 4 ,date:'11 June 2019',bank:'Canara Bank',txid:'76jhdg74rh4h848r58'}, { key:'7',myx: 'July', step: 3, c0: 1 ,date:'28 July 2019',bank:'Punjab National Bank',txid:'76jhdg74rh4h848r58'}, ];
Step 2: Configure Victory Components to Use Custom Keys
Victory Native lets you explicitly map your data keys to the chart axes using props on your data visualization component (like VictoryBar, VictoryLine, etc.) and axis components. Here's a complete example with a bar chart:
import React from 'react'; import { VictoryChart, VictoryBar, VictoryAxis } from 'victory-native'; export default function CustomKeyChart() { return ( <VictoryChart> {/* X-axis: Use `myx` values for ticks */} <VictoryAxis xAccessor={(datum) => datum.myx} tickFormat={(tick) => tick} // Preserve the month labels /> {/* Y-axis: Defaults to numeric values from `step` */} <VictoryAxis dependentAxis /> {/* Bar series: Map `myx` to x-axis and `step` to y-axis */} <VictoryBar data={sampleData} x="myx" // Directly reference the custom x key y="step" // Directly reference the custom y key /> </VictoryChart> ); }
For More Control: Use Accessor Functions
If you need to transform data before rendering (e.g., formatting dates or calculating values), use xAccessor and yAccessor instead of string keys:
<VictoryBar data={sampleData} xAccessor={(datum) => datum.myx} // Extracts the `myx` value from each data point yAccessor={(datum) => datum.step} // Extracts the `step` value from each data point />
This approach works for any Victory Native chart type (lines, areas, scatter plots) — just apply the same x/y props or accessor functions to your chosen data component.
内容的提问来源于stack exchange,提问作者Rajat Verma

