How to position these dataLabels to the right of a horizontal bar chart

192 views Asked by At

I'm trying to render a horizontal bar chart with the data labels to the right of the bars, but the best I have achieved so far is the labels half inside the bar and half outside:

screenshot of the problematic chart

Here is the chart option:

 this.chart = {
      series: [
        {
          name: 'Sample',
          data: [37.9, 21.8, 8.6],
        },
      ],
      chart: {
        type: 'bar',
        fontFamily: "'Plus Jakarta Sans', sans-serif;",
        foreColor: '#adb0bb',
        height: 380,
        stacked: true,
        toolbar: {
          show: false,
        },
      },
      plotOptions: {
        bar: {
          horizontal: true,
          borderRadius: 4,
          columnWidth: '40%',
          barHeight: '40%',
          endingShape: 'rounded',
          dataLabels: {
            position: 'end',
          },
        },
      },
      markers: {
        size: 3,
      },
      stroke: {
        curve: 'straight',
        width: '0',
      },
      colors: ['#763EBD'],
      legend: {
        show: true,
      },
      grid: {
        show: true,
        strokeDashArray: 0,
        borderColor: 'rgba(0,0,0,0.1)',
        xaxis: {
          lines: {
            show: true,
          },
        },
        yaxis: {
          lines: {
            show: true,
          },
        },
      },
      xaxis: {
        type: 'category',
        categories: ['Label 1', 'Label 2', 'Label 3'],
      },
      tooltip: {
        theme: 'dark',
      },
      dataLabels: {
        enabled: true,
        formatter: function (val: number) {
          return val.toString().concat('%');
        },
        style: {
          colors: ['#000'],
        },
      },
    };

And here's the HTML:

<apx-chart
    [series]="chart.series"
    [chart]="chart.chart"
    [xaxis]="chart.xaxis"
    [yaxis]="chart.yaxis"
    [grid]="chart.grid"
    [stroke]="chart.stroke"
    [tooltip]="chart.tooltip"
    [plotOptions]="chart.plotOptions"
    [dataLabels]="chart.dataLabels"
    [legend]="chart.legend"
    [colors]="chart.colors"
    [markers]="chart.markers"
>
</apx-chart>

I've tried:

  • Adding offsetX values to dataLabels and to the one under plotOptions > bar
  • Changing the position inside both dataLabels objects
1

There are 1 answers

0
Yong Shun On BEST ANSWER

You should set the plotOptions.bar.dataLabels.position as "top".

plotOptions: {
  bar: {
    ...,
    dataLabels: {
      position: 'top'
    }
  }
}

And provide the dataLabels.offsetX with the desired value.

dataLabels: {
  ...,
  offsetX: 50
}

Also, you may use textAnchor for the text-align.

dataLabels: {
  ...,
  offsetX: 25,
  textAnchor: "start"
}

Demo @ StackBlitz

enter image description here

Reference: DataLabels (DataLabels offset section)