Search code examples
javascriptchart.jsquickchart

Bar chart with two sets of labels in Quickchart


I am trying to create a bar chart for tracking a budget with quickchart. I want the chart to have one set of labels on top of the bars (for % remaining), and a second set of labels inside each bar (for $'s remaining).

I was able to figure out the labels on top of the bars, but need help adding a second set of labels within the bars. The labels within the bars will need to be based on a second array of data.

I have posted my code, which can be tweaked in the live editor here. Any help would be greatly appreciated!

{
  type: 'bar',
  data: {
    labels: ['Food', 'Gas', 'Other'],
    datasets: [{
      label: 'Category',
      data: [.5, .7, .8]
    }]
  },
  options: {
        plugins: {
      datalabels: {
        formatter: function(value) {
            return Math.round(value*100) + '%';},
        anchor: 'end',
        align: 'end',
        color: 'black',
        labels: {
          percent: {
            font: {
              weight: 'bold',
              size:26,
            }
          }
        }
      }
    },
    scales: {
      yAxes: [ {
        type: 'linear',
        ticks: {
            beginAtZero: true,
            suggestedMin : 0,
            suggestedMax : 1,
            }
        }]
      } 
  }
}

Solution

  • Beside datalabels.labels.percent, you could also define datalabels.labels.value, both with specific formatter and positioning. No need to define a second dataset, simply define amountRemaining inside the existing dataset and reference it in the corresponding formatter.

    This could look as follows...

    {
      type: 'bar',
      data: {
        labels: ['Food', 'Gas', 'Other'],
        datasets: [{
          label: 'Category',
          data: [.5, .7, .8],
          amountRemaining: [300, 420, 480]
        }]
      },
      options: {
        plugins: {
          datalabels: {
            color: 'black',
            labels: {
              percent: {
                formatter: v => Math.round(v * 100) + '%',
                anchor: 'end',
                align: 'end',
                font: {
                  weight: 'bold',
                  size: 26,
                }
              },
              value: {
                formatter: (v, ctx) => ctx.chart.data.datasets[0].amountRemaining[ctx.dataIndex] + '$',
                font: {
                  weight: 'bold',
                  size: 26,
                }
              }
            }
          }
        },
        scales: {
          yAxes: [{
            type: 'linear',
            ticks: {
              beginAtZero: true,
              suggestedMin: 0,
              suggestedMax: 1,
            }
          }]
        }
      }
    }