LeetCoder
LeetCoder

Reputation: 603

Understanding Chart.js and Adding Legends to Pie Charts

I've been learning to use Chart.js through examples, and I was looking at this website's examples:

https://pythonspot.com/flask-and-great-looking-charts-using-chart-js/

I'm trying to see how I can add a legend to their pie chart, and from the documentations/other posts I read, it looks like I need to add an

This is what the code for the pie chart currently looks like:

# Variables passed onto render_template() in Flask:
values = [1, 2, 3, 4, 5, 6, 7]
labels = ["A", "B", "C", "D", "E", "F", "G"]
colors = ["#F7464A", "#46BFBD", "#FDB45C", "#FEDCBA","#ABCDEF", "#DDDDDD", "#ABCABC"]

set = zip(values, labels, colors]

The JavaScript code:

<canvas id="chart" width="600" height="400"></canvas>
<script>
  var pieData = [
    {% for item, label, colors in set %}
      {
        value: {{item}},
        label: "{{label}}",
        color : "{{colors}}"
      },

    {% endfor %}
  ];
  // get bar chart canvas
  var mychart = document.getElementById("chart").getContext("2d");
  steps = 10
  max = {{ max }}

  // draw pie chart
  new Chart(document.getElementById("chart").getContext("2d")).Pie(pieData);
</script>

From what I understand, I need to add an options tag with generateLabel() somewhere in the script, but I have no clue where. All other examples of Chart.js pie charts, use a completely different method in generating the graphs, and while I do understand those, I don't quite understand the method above. Where should I be adding the options tag here? Thank you.

Upvotes: 0

Views: 1865

Answers (1)

Martin Zeitler
Martin Zeitler

Reputation: 76669

var values = [1, 2, 3, 4, 5, 6, 7];
var labels = ["A", "B", "C", "D", "E", "F", "G"];
var colors = ["#F7464A", "#46BFBD", "#FDB45C", "#FEDCBA","#ABCDEF", "#DDDDDD", "#ABCABC"];


var chart = new Chart(document.getElementById("chart"), {
    type: 'pie',
    data: {
      labels: labels,
      datasets: [{
        label: "Series 01",
        backgroundColor: colors,
        data: values
      }]
    },
    options: {
      title: {
        display: true,
        text: 'just a code snippet ...'
      },
      legend: {
        labels: {
          /* here one can adjust the legend's labels, if required */
          // generateLabels: function(chart) {}
        }
      }
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<canvas id="chart" width="100%" height="100%"></canvas>

that legend is even click-able, so that one can hide/show specific values.

Upvotes: 1

Related Questions