Formatting doughnut/pie chart labels

A couple people have asked me recently about altering their doughnut charts. The easiest way to do this is with the chartjs-plugin-datalabels plugin, which is automatically included in all QuickChart renders.

See this post for more information on customizing doughnut and pie charts.

Here’s an example:

{
  type: 'doughnut',
  data: {
    datasets: [
      {
        data: [10, 20, 15, 5, 50],
      },
    ],
    labels: ['A', 'B', 'C', 'D', 'E'],
  },
  options: {
    plugins: {
      datalabels: {
        formatter: (value) => {
          return value + '%';
        }
      }
    }
  }
}

Feel free to respond to this post if you have more questions about customizing your doughnut and pie charts.

1 Like

image

Fantastic! :heart_eyes:

This is definitely something I’ll be making use of! Thank you so much!

1 Like

Hello!

I’m trying to replicate this in Python. I can’t add

formatter: (value) => {
          return value + '%';
        }

this in a dict for obvious reasons. I know I can pass the config as a string, but that means some messy code to have non-fixed data. Is there a better way to do this?

Hi @piechart,

The easiest way to do this is using the quickchart-python library. It is available as a package via pip install quickchart.io

The library allows you to use QuickChartFunction like so:

from quickchart import QuickChart, QuickChartFunction

qc = QuickChart()
qc.config = {
    "type": "doughnut",
    "data": {
        "labels": ['A', 'B', 'C', 'D', 'E'],
        "datasets": [{
            "data": [10, 20, 15, 5, 50]
        }]
    },
    "options": {
        "plugins": {
            "datalabels": {
                "formatter": QuickChartFunction('(val) => val + "%"')
            }
        }
    }
}

print(qc.get_url())

If you’re not using the library, you’ll ultimately have to send the chart config as a string.

One workaround that I’ve seen some people use to keep things cleaner: you could set formatter to some placeholder value like __FORMATTER_FUNCTION__, serialize your dict to JSON, and then do a string replacement on "__FORMATTER_FUNCTION__".

Hope this helps!

1 Like

Thank you! Exactly what I was looking for :slight_smile: