0

I am trying to create a donut chart with chart.js using data from csv file. Following is my script so far, but it is not working. Any guidance is appreciated on the same.

<script>
var file='donut.csv';
d3.csv(file).then(makeChart); //use d3.csv to read file
function makeChart(types){
var can=types.map(function(d){return d.cancelled});
var suc=types.map(function(d){return d.success});
var fa=types.map(function(d){return d.failed});
 {
var chart=new Chart(document.getElementById("doughnut-chart"), {
    type: 'doughnut',
    data: {
        labels: ["Cancelled","Success", "Failed"],
      datasets: [
        {
          label: "Population (millions)",
          backgroundColor: ["#3e95cd", "#3cba9f","#8e5ea2"],
          data: [can,suc,fa]
        }
      ]
    },
    options: {
      title: {
        display: true,
        text: 'Weekly  Status'
      }
    }
}
}
);
</script>

and my donut.csv looks like as below:

cancelled,300,
success,1000,
failed,20,
0

1 Answer 1

1

Since your CSV data has no header, you should use d3.text to load the data, followed by d3.csvParseRows to parse it to a JSON array (see https://stackoverflow.com/a/13870360/2358409). To extract the data values from the JSON array, you can use Array.map.

data: d3.csvParseRows(types).map(v => v[1])

Please take a look at your amended code and see how it works.

d3.text("https://raw.githubusercontent.com/uminder/testdata/main/so/csv/donut.csv").then(makeChart);
function makeChart(types) {
  new Chart('doughnut-chart', {
    type: 'doughnut',
    data: {
      labels: ['Cancelled', 'Success', 'Failed'],
      datasets: [{
        label: 'Population (millions)',
        backgroundColor: ['#3e95cd', '#3cba9f', '#8e5ea2'],
        data: d3.csvParseRows(types).map(v => v[1])
      }]
    },
    options: {
      title: {
        display: true,
        text: 'Weekly  Status'
      }
    }
  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/6.2.0/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<canvas id="doughnut-chart" height="90"></canvas>

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot Uminder for improved code and pointing the missing piece. If you do not mind, plesae can you tell me in case my csv changes, how do I update chart with new data ? calling just update() function ?
@Novice: Please take a look at the following answers that deal with chart.update(): stackoverflow.com/a/61025107/2358409 and stackoverflow.com/a/61576710/2358409

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.