在水平 Victory 条形图中定位 y 轴标签

时间:2021-06-04 09:43:36

标签: victory-charts

我在使用水平条的 VictoryChart 中遇到布局问题。我正在尝试将下面垂直轴上的标签左对齐:

horizontal bar chart with malaligned labels

我使用的相关代码是

<VictoryChart domainPadding={{ x: [20, 20] }}>
  <VictoryAxis
    dependentAxis={true}
    tickValues={[0, 2, 4, 6, 8, 10, 12, 14]}
  />
  <VictoryAxis
    labelComponent={<VictoryLabel textAnchor="start" />}
    style={{
      tickLabels: {
        fontSize: 10,
        textAnchor: "end"
      }
    }}
  />
  <VictoryBar
    data={data}
    horizontal={true}
    domain={{ y: [-10, 15] }}
    x="name"
    y="value"
  />
</VictoryChart>

我创建了一个沙盒 here

我必须先添加 tickLabels 样式 textAnchor: "end" 才能使标签可见现在。我尝试将 labelComponent 定义为 <VictoryLabel textAnchor="start" /> 但这并没有达到我希望的效果。在检查生成的 SVG 时,该 SVG 似乎控制文本在其容器元素中的锚定方式,但我在这里真正需要做的是将整个容器向左移动。

我已多次浏览 API 文档,但没有发现任何看起来有用的内容。 VictoryGroup 看起来很有希望,但文档特别告诉我不要将它与轴组件一起使用。

1 个答案:

答案 0 :(得分:0)

好吧,我只是迷失在道具丛林中。

解决方案首先是不要尝试使用 CSS 样式来执行此操作,因此必须使用 tickLabels.textAnchor: "end" 样式。其次,标签组件不止一个,对于 VictoryAxis 上的标签,相关属性是 tickLabelComponent 而不是 labelComponent

替换第二个VictoryAxis组件
<VictoryAxis
    tickLabelComponent={(
      <VictoryLabel
          verticalAnchor="middle"
          textAnchor="start"
          x={0}
      />
  )}
  style={{
    tickLabels: {
      fontSize: 10,
    }
  }}
/>

解决了我的问题。