Search code examples
pythonpygal

Using PyGal, how can I embed a label on the pie chart itself on hover?


Using the code below, I can generate a pie chart. When I hover over a slice of the pie, it shows the percentage that slice occupies.

import pygal
results = [
    (15232,'Value 1'),
    (947,'Value 2'),
    (246,'Value 3'),
    (117,'Value 4'),
    (50,'Value 5'),
    (50,'Value 6'),
    (50,'Value 7'),
    (50,'Value 8'),
]

pie_chart = pygal.Pie()
pie_chart.title = 'Title!'
for r in results:
    pie_chart.add(r[1], r[0])
pie_chart.value_formatter = lambda x: "%.15f" % x
pie_chart.render_to_file('piechart.svg')

This produces a pie chart that looks like this (if I hover over "Value 2"):

PyGal Default Pie Chart

The problem I have is with the small slices. It's very hard to see what I am hovering over. In the example above, this is especially obvious with Values 5 through 8, but even on Value 4, it's hard to tell which one is being hovered above. Is there a way to include the label in the tool tip as well?

The closest I've found is value_formater, but this seems to be ignored in pie charts (as evidenced by the example above only having 2 decimal places in the tooltip, despite the pie_chart.value_formatter = lambda x: "%.15f" % x line of code).


Solution

  • The solution to this was to utilize the label metadata information. This requires that a dictionary, instead of a single value, be passed as the second parameter to the .add() in the for loop.

    for r in results:
        pie_chart.add(r[1], [{'value': r[0], 'label': r[1]}])