Having trouble with Pie Chat not displaying on my browser while working on D3 integration with basic HTML

I am struggling to get my Pie chart created using D3.JS to show up when I load my file in Chrome or any browser (index.html). It only displays the title without the actual pie chart.

I'm not sure where the issue lies and why my pie chart is not appearing. Any assistance on this matter would be greatly appreciated. Thank you.

style.css -

.arc text {
  font: 10px sans-serif;
  text-anchor: middle;
}

.arc path {
  stroke: #fff;
}

.arc2 text {
  font: 10px sans-serif;
  text-anchor: middle;
}

.arc2 path {
  stroke: #fff;
}

pie.js -

// margin
var margin = {top: 20, right: 20, bottom: 20, left: 20},
    width = 500 - margin.right - margin.left,
    height = 500 - margin.top - margin.bottom,
    radius = width/2;

// color range
var color = d3.scaleOrdinal()
    .range(["#BBDEFB", "#90CAF9", "#64B5F6", "#42A5F5", "#2196F3", "#1E88E5", "#1976D2"]);

// pie chart arc. Need to create arcs before generating pie
var arc = d3.arc()
    .outerRadius(radius - 10)
    .innerRadius(0);

// donut chart arc
var arc2 = d3.arc()
    .outerRadius(radius - 10)
    .innerRadius(radius - 70);

// arc for the labels position
var labelArc = d3.arc()
    .outerRadius(radius - 40)
    .innerRadius(radius - 40);

// generate pie chart and donut chart
var pie = d3.pie()
    .sort(null)
    .value(function(d) { return d.count; });

// define the svg for pie chart
var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height)
  .append("g")
    .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

// define the svg donut chart
var svg2 = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height)
  .append("g")
    .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

// import data 
d3.csv("data.csv", function(error, data) {
  if (error) throw error;

    // parse data
    data.forEach(function(d) {
        d.count = +d.count;
        d.fruit = d.fruit;
    })

  // "g element is a container used to group other SVG elements"
  var g = svg.selectAll(".arc")
      .data(pie(data))
    .enter().append("g")
      .attr("class", "arc");

  // append path 
  g.append("path")
      .attr("d", arc)
      .style("fill", function(d) { return color(d.data.fruit); })
    // transition 
    .transition()
      .ease(d3.easeLinear)
      .duration(2000)
      .attrTween("d", tweenPie);

  // append text
  g.append("text")
    .transition()
      .ease(d3.easeLinear)
      .duration(2000)
    .attr("transform", function(d) { return "translate(" + labelArc.centroid(d) + ")"; })
      .attr("dy", ".35em")
      .text(function(d) { return d.data.fruit; });


    // "g element is a container used to group other SVG elements"
  var g2 = svg2.selectAll(".arc2")
      .data(pie(data))
    .enter().append("g")
      .attr("class", "arc2");

   // append path 
  g2.append("path")
      .attr("d", arc2)
      .style("fill", function(d) { return color(d.data.fruit); })
    .transition()
      .ease(d3.easeLinear)
      .duration(2000)
      .attrTween("d", tweenDonut);

   // append text
  g2.append("text")
    .transition()
      .ease(d3.easeLinear)
      .duration(2000)
    .attr("transform", function(d) { return "translate(" + labelArc.centroid(d) + ")"; })
      .attr("dy", ".35em")
      .text(function(d) { return d.data.fruit; });

});

// Helper function for animation of pie chart and donut chart
function tweenPie(b) {
  b.innerRadius = 0;
  var i = d3.interpolate({startAngle: 0, endAngle: 0}, b);
  return function(t) { return arc(i(t)); };
}

function tweenDonut(b) {
  b.innerRadius = 0;
  var i = d3.interpolate({startAngle: 0, endAngle: 0}, b);
  return function(t) { return arc2(i(t)); };
}

CSV file (data.csv)

fruit,count
Apple,10
Strawberry,20
Banana,15
Blueberry,20,
Kiwi,30
Plum,5

index.html

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Pie Charts</title>

        <!-- Stylesheet -->
        <link rel="stylesheet" type="text/css" href="css/style.css">

        <!-- Load D3 -->
        <script src="//d3js.org/d3.v4.min.js" charset="utf-8"></script>




    </head>
    <body>
        <h2>Pie Chart and Donut Chart</h2>

        <script type="text/javascript" src="js/pie.js"></script>


    </body>

</html>

Answer №1

One reason for this issue is that chrome restricts Cross origin requests from loading files, except for certain protocol requests. To overcome this limitation, you can run it on an app server (e.g. tomcat or jboss), or use alternative browsers like Firefox which allow running local files seamlessly.

If you encounter any errors, always check the console as there may not be an issue with your code every time. In Chrome, when opening the HTML file, you might see the following message:

d3.v4.min.js:7 
XMLHttpRequest cannot load file:///C:/Users/sidd/Desktop/New%20folder/data.csv. 
Cross origin requests are only supported for protocol schemes: http, data,       
chrome, chrome-extension, https.

This error occurs because file:///Drive:/ is not included in the list of protocols supported by Chrome, hence causing the problem.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be the reason for the full name not being updated in the model when the last name is changed

Can you explain why the full name in the model does not update when I change the last name? You can view the code on Plunker: http://plnkr.co/edit/cqmwJc5dpoDWvai4xeNX?p=preview var loginCntrl=function($scope){ $scope.testClick =function(){ $scope. ...

The transmission of information through Ajax is encountering a problem as the data is not properly

Having some trouble using Ajax to send form data and echoing it on the PHP page. Since I'm new to Ajax, I might have made a mistake somewhere in my code. Below is what I currently have: $(function () { $('form').on('submit&apos ...

Setting a one-month date range in Bootstrap Material date picker - a simple guide

Is it possible to configure a 1-month date range in the Bootstrap Material date picker? Check out this link for more information ...

Double Checkbox

My current project involves creating an update page, and I have successfully completed most of it except for the checkbox section. Strangely, the checkboxes are being duplicated, and I haven't been able to identify the reason behind this issue yet. Th ...

What is the reason that the ES6 module import expression fails to import JSON files located in the assets folder when using certain path arguments?

A puzzling ES6 import scenario came up where the following import statement did not function as expected within methods of a Vue.js SFC: const fullContentFile = '@/assets/rules/rules.json' import(fullContentFile).then(data => console.log(&apos ...

I need some assistance, please. Can someone explain why the Bootstrap card is staying aligned to the left in mobile view

I've tried everything, but it's still not working. Can anyone help me out? Here are some photos. BEFORE AFTER When I view the card on mobile, I want it to stay centered. Could there be some missing code that I'm overlooking? I would great ...

"Exploring the power of Knockout JS by utilizing the foreach loop to iterate through

I have an observableArray: self.stats = ko.observableArray([ {"DFTD" : new Stat("Defensive TD", "DFTD",0,20,0,self.playerGroups[1])}, {"GL" : new Stat("Games Lost", "GL",0,16,0,self.playerGroups[2])}, {"FGA" : new Stat("Field Go ...

Show the cell data when the checkbox next to it is selected

I have a specific table setup and I am trying to display the content of the table cell if its corresponding checkbox is checked upon clicking a button. For example: If Row2 is checked, an alert box should display Row2 Below is my code snippet, Java ...

Duplicate the PHP code for every section found within an INI file

<? $config = parse_ini_file('/list.ini', true); ?> <?echo'<select id="LBox" name="listbox" size="20" style="display:none;">'; foreach($config[MPR] as $id=>$label){ switch ($id) { case ($id== ...

This TypeScript error occurs when the props are not compatible and cannot be assigned to

Hello fellow Internet dwellers! I am a novice in the world of coding and TypeScript, seeking some assistance here. I am attempting to extract an array of objects from props, transform it into a new object with specific information, and then return it - ho ...

Is the ng-style not displaying the background image with the interpolated value?

I have been attempting to update the background image of a div using angular ng-style. Below is the code I am working with: <div class="cover-image" ng-style="{'background-image' : 'url({{data.image}})'}"></div> However, ...

Is it possible to have two different actions with two submit buttons in PHP?

Here is my form tag: sample name:register.php page <form id="formElem" name="formElem" action="form10.php" method="post"> <input id="pd" name="pd" type="text" AUTOCOMPLETE=OFF /> <input id="pd1" name="fname" type="text" AUTOCOMPLETE=OFF /& ...

Tips for creating a versatile generic function in javascript that covers all arguments sizes

When working with node.js, a tcp server typically has several methods for listening: server.listen(port, [host], [backlog], [listeningListener]) server.listen(path, [listeningListener]) server.listen(handle, [listeningListener]) In the context of creatin ...

Is it possible to use an image loaded as a texture to create another texture mipmap in three.js?

This is not a problem, it's simply a question. Currently, I am working on a terrain project using an atlas texture. In order to reduce color bleeding, I am planning to create mipmaps externally and then apply them to the terrain texture. At the mome ...

What's the best way to toggle the visibility of an input-group in Bootstrap?

Is there a way to properly hide and show a Bootstrap 5 input-group? You can see an example here: https://jsfiddle.net/o08r3p9u I'm facing an issue where once the input group is hidden, it doesn't show correctly when displayed again. How can I e ...

Is it possible to manipulate a modal within a controller by utilizing a certain attribute in HTML, based on specific conditions (without relying on any bootstrap services), using AngularJS?

Within my application, I have a modal that is triggered by clicking on a button (ng-click) based on certain conditions. Here is the HTML code: <button type="button" class="btn btn-outlined" ng-click="vm.change()" data-modal-target="#add-save-all-alert ...

Collapsible List Group Button Utilizing Bootstrap Remains Expanded

Looking for some guidance here. I am just starting out with Bootstrap and trying to learn from their website, but I'm having trouble figuring out how to make something collapsed. I found collapse.js, jquery.min.js, bootstrap.min.js, and transition.js ...

Setting up Type ORM configuration with a .env file in Nest.JS: A step-by-step guide

I encountered an issue while attempting to configure TypeORM with a .env file and run migration script. Here's what I tried: 1. Added scripts to package.json "migration:generate": "node_modules/.bin/typeorm migration:generate -n", "migratio ...

Encountering issues with React Apollo hooks after integrating React Native into the monorepo system

I am in the process of setting up a React web app and a React-native app within a monorepo using yarn workspaces. The web and controllers are functioning properly, allowing me to successfully execute graphql queries to my apollo-express server. However, up ...

Creating dynamic buttons based on a list: A step-by-step guide

Is there a way to dynamically generate and display buttons based on the number of elements in a list? I currently have a hardcoded implementation, but sometimes my list only contains two elements (button 1 and button 2) so I don't need the additional ...