首页 > 解决方案 > 如何使用 Victory Charts 特别是 Victory Candlestick 错开 x 轴值

问题描述

我正在 React Native 中构建一个应用程序,并使用 Victory Candlestick 图表来显示来自 Alpha Vantage 的股票的(开盘价、最高价、最低价、收盘价)OHLC 数据。当我将数据传递给图表时,图表会显示蜡烛,但 x 轴值太多并且相互重叠。结果图表的图像如下所示:在此处输入图像描述

如何更改 x 轴以呈现刻度月份(“jan”、“feb”、“mar”等)?

生成此图表的代码如下所示:

 <VictoryChart
                theme={VictoryTheme.material}
                domainPadding={{ x: 25 }}
                scale={{ x: 'time' }}
              >
                <VictoryAxis
                  // tickValues={[5, 6, 7, 8, 9, 10, 11, 12]}
                  // domain={{x: [0, 100]}}
                  scale='time'
                  // tickFormat={(t) => `${t}`}
                  // tickFormat={(t) => `${t.slice(0, 2)}`}
                  tickFormat={(t) => new Date(t).getFullYear()}
                />
                <VictoryAxis
                  dependentAxis
                  axisLabelComponent={<VictoryLabel dx={20} />}
                />
                <VictoryCandlestick
                  candleColors={{ positive: '#336d16', negative: '#ff0000' }}
                  data={this.state.ordered_data}
                />
              </VictoryChart>

传递给 VictoryCandlestick 的数据(代码中称为 this.state.ordered_data)的形状如下:

    {Object {
    "close": 54.58,
    "high": 55.19,
    "low": 53.7,
    "open": 54.56,
    "x": "2021-02-03",
  },
  Object {
    "close": 54,
    "high": 54.87,
    "low": 52.71,
    "open": 52.865,
    "x": "2021-02-02",
  },
  Object {
    "close": 52.66,
    "high": 52.75,
    "low": 51.0718,
    "open": 51.2,
    "x": "2021-02-01",
  },}

包含所有这些代码的 GitHub 存储库在这里:项目的 Github存储库,此屏幕的代码位于/screens文件夹中的 StockScreen.js 文件中。

标签: javascriptreactjsreact-nativevictory-charts

解决方案


如下修改 Victory Charts 代码可修复该问题:

<VictoryChart
                theme={VictoryTheme.material}
                domainPadding={{ x: 25 }}
                scale={{ x: 'time' }}
              >
                <VictoryAxis
                  scale='time'
                  tickFormat={(t) => `${t}`}
                  fixLabelOverlap
                  style={{ tickLabels: { padding: 16, fontSize: 8 } }}
                />
                <VictoryAxis
                  dependentAxis
                  axisLabelComponent={<VictoryLabel dx={20} />}
                />
                <VictoryCandlestick
                  candleColors={{ positive: '#336d16', negative: '#ff0000' }}
                  data={this.state.ordered_data}
                />
              </VictoryChart>

fixLabelOverlapand属性添加style={{ tickLabels: { padding: 16, fontSize: 8 } }}到 VictoryAxis 组件专门解决了这个问题。


推荐阅读