Search code examples
victory-charts

Positioning y-axis labels in a horizontal Victory bar chart


I'm having issues with the layout in a VictoryChart using horizontal bars. I'm trying to left align the labels on the vertical axis below:

horizontal bar chart with malaligned labels

The relevant bits of code I'm using is

<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>

And I've created a sandbox here.

I had to add the tickLabels style textAnchor: "end" to get the labels to be visible in the first place but I would very much like them to align to a common left vertical line, not right like they are now. I tried by defining a labelComponent as <VictoryLabel textAnchor="start" /> but this did not have the effect I hoped for. Upon inspecting the generated SVG that seems to control how the text is anchored within it's container element but what I really need to do here is moving the entire container to the left.

I've gone through the API documentation several times but haven't been able to spot anything that looks like it would be useful. VictoryGroup looked promising but the docs specifically tell me not to use it with the axis component.


Solution

  • OK so I was just getting lost in the jungle of props here.

    The solution was first to not try to do this using CSS styles, so the tickLabels.textAnchor: "end" style had to go. Secondly, there's more than one label-component and for the labels on the VictoryAxis the relevant property is tickLabelComponent and not labelComponent.

    Replacing the second VictoryAxis component with

    <VictoryAxis
        tickLabelComponent={(
          <VictoryLabel
              verticalAnchor="middle"
              textAnchor="start"
              x={0}
          />
      )}
      style={{
        tickLabels: {
          fontSize: 10,
        }
      }}
    />
    

    Fixes my issue.