Illustration of a D3 graph demo

I'm currently working on modifying a d3.js graph example originally created by Mike Bostock. My goal is to replace the d3.csv method with d3.json. I made adjustments to parts of the original code, but unfortunately, my graph has disappeared without any apparent errors. I'm not sure what went wrong.

The HTML Code:

 <!DOCTYPE html>

<head>
    <title> Graphical Representation </title>
    <script src="d3.js" charset="utf-8"></script>
    <script src="d3.min.js" charset="utf-8"></script>
</head>

<body>

<svg width="960" height="500"></svg>
<script>
    var svg = d3.select("svg"),
        margin = {
            top: 20,
            right: 20,
            bottom: 30,
            left: 60
        },
        width = +svg.attr("width") - margin.left - margin.right,
        height = +svg.attr("height") - margin.top - margin.bottom,
        g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    var parseDate = d3.timeParse("%Y%m%d"),
        formatDate = d3.timeFormat("%Y");

    var x = d3.scaleTime()
        .domain([new Date(1999, 0, 1), new Date(2003, 0, 0)])
        .range([0, width]);

    var y = d3.scaleLinear()
        .range([height, 0]);

    var xAxis = d3.axisBottom(x);

    var yAxis = d3.axisLeft(y);

    var area = d3.area()
        .curve(d3.curveStepAfter)
        .y0(y(0))
        .y1(function(d) {
            return y(d.NbCopie);
        });

    var areaPath = g.append("path")
        .attr("clip-path", "url(#clip)")
        .attr("fill", "steelblue");

    var yGroup = g.append("g");

    var xGroup = g.append("g")
        .attr("transform", "translate(0," + height + ")");

    var zoom = d3.zoom()
        .scaleExtent([1 / 4, 8])
        .translateExtent([
            [-width, -Infinity],
            [2 * width, Infinity]
        ])
        .on("zoom", zoomed);

    var zoomRect = svg.append("rect")
        .attr("width", width)
        .attr("height", height)
        .attr("fill", "none")
        .attr("pointer-events", "all")
        .call(zoom);

    g.append("clipPath")
        .attr("id", "clip")
        .append("rect")
        .attr("width", width)
        .attr("height", height);

    d3.json("data.json", function(d) {
        d.Date_Id = parseDate(d.Date_Id);
        d.NbCopie = +d.NbCopie;
        return d;
    }, function(error, data) {
        if (error) throw error;
        var xExtent = d3.extent(data, function(d) {
            return d.Date_Id;
        });
        zoom.translateExtent([
            [x(xExtent[0]), -Infinity],
            [x(xExtent[1]), Infinity]
        ])
        y.domain([0, d3.max(data, function(d) {
            return d.NbCopie;
        })]);
        yGroup.call(yAxis).select(".domain").remove();
        areaPath.datum(data);
        zoomRect.call(zoom.transform, d3.zoomIdentity);
    });

    function zoomed() {
        var xz = d3.event.transform.rescaleX(x);
        xGroup.call(xAxis.scale(xz));
        areaPath.attr("d", area.x(function(d) {
            return xz(d.Date_Id);
            }));
    }
    </script>
</body>

</html>

Here is the json file content:

[
{
    "ConsoPhot_Id": "10148",
    "idLotImport": 390,
    "Date_Id": 20170201,
    "Orga_Id": "203938",
    "NbTache": 153,
    "NbCopie": 798,
    "NbCopieBW": 488,
    "NbCopieCouleur": 310,
    "MtTotal": 13.69
},
{
    "ConsoPhot_Id": "10602",
    "idLotImport": 391,
    "Date_Id": 20161201,
    "Orga_Id": "203938",
    "NbTache": 153,
    "NbCopie": 909,
    "NbCopieBW": 779,
    "NbCopieCouleur": 130,
    "MtTotal": 7.93
},
{
    "ConsoPhot_Id": "10905",
    "idLotImport": 392,
    "Date_Id": 20161101,
    "Orga_Id": "203938",
    "NbTache": 115,
    "NbCopie": 515,
    "NbCopieBW": 409,
    "NbCopieCouleur": 106,
    "MtTotal": 5.6
},
{
    "ConsoPhot_Id": "11162",
    "idLotImport": 393,
    "Date_Id": 20161001,
    "Orga_Id": "203938",
    "NbTache": 233,
    "NbCopie": 1173,
    "NbCopieBW": 725,
    "NbCopieCouleur": 448,
    "MtTotal": 19.86
},
{
    "ConsoPhot_Id": "11745",
    "idLotImport": 394,
    "Date_Id": 20170101,
    "Orga_Id": "203938",
    "NbTache": 173,
    "NbCopie": 889,
    "NbCopieBW": 782,
    "NbCopieCouleur": 107,
    "MtTotal": 7.07
},
{
    "ConsoPhot_Id": "12144",
    "idLotImport": 435,
    "Date_Id": 20170301,
    "Orga_Id": "203938",
    "NbTache": 131,
    "NbCopie": 590,
    "NbCopieBW": 454,
    "NbCopieCouleur": 136,
    "MtTotal": 6.92
}
]

Answer №1

(It's interesting to note that this seems like a duplicate. Ironically, my attempts to close this question were unsuccessful because none of my multiple answers had been accepted or upvoted)

The problem at hand is actually quite straightforward: unlike the d3.csv function, the d3.json function does not support a row function.

In your specific scenario...

d3.json("data.json", function(d) {
            d.Date_Id = parseDate(d.Date_Id);
            d.NbCopie = +d.NbCopie;
            return d;
        }, function(error, data) {

...the function right after "data.json" and before function(error, data) serves as the row function.

Solution: Simply do the following:

d3.json("data.json", function(error, data) {

Then, move the row function inside a forEach within the callback:

data.forEach(function(d) {
    d.Date_Id = parseDate(d.Date_Id);
    d.NbCopie = +d.NbCopie;
})

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

Ways to retrieve a JSON formatted list using Struts 2

In my quest for a JSON list page, I'm utilizing Hibernate+Struts and have integrated the JSON Struts2 plugin into my build path. Although I've configured my struts.xml, I keep encountering the same ERRORS. How can I implement JSON authentication ...

What could be causing my Ionic button to not initialize in the expected state while using ngIf with a boolean property connected to an Ionic checkbox?

I'm currently in the process of setting up a list of ingredients with checkboxes and conditional buttons, but I'm facing some challenges with the default state. Ideally, I only want the button to be visible when the checkbox is unchecked so that ...

The json-server-auth feature is failing to function properly upon initialization

I recently attempted to use json-server-auth by installing it via npm, but encountered a problem when trying to start it. The error message I received is as follows: json-server-auth : The term 'json-server-auth' is not recognized as the name ...

What is the best way to add a hyperlink to a cell in an Angular Grid column

I need help creating a link for a column cell in my angular grid with a dynamic job id, like /jobs/3/job-maintenance/general. In this case, 3 is the job id. I have element.jobId available. How can I achieve this? Here is the code for the existing column: ...

Tallying the number of words delimited by a comma

Here is how my counter function is structured: function count() { var value = ids.val(); return (value == '') ? 0 : value.replace(/\s,?|,$/g, '').split(',').length; } After checking the returned value, data is ...

"Encountered an error stating 'undefined method `each` for nil:NilClass' while working with an API

I've encountered a common error that I can't seem to troubleshoot. My goal is to access the ProPublica API for congress, but despite having a straightforward model, view, and controller setup, I keep running into issues. Interestingly, this same ...

What is the best way to incorporate a fadeIn animation to a text in jQuery?

Looking for help with appending the fadeIn() jQuery function to a string that increments an integer within a paragraph. I attempted concatenation without success. Any recommendations on how to solve this issue? $p.text(parseInt($p.text(),10) + 1); ...

Implement a termination condition for mapping in React

Here is a code snippet to consider: <TableHead> {documents.map((docs, i) => ( <TableRow key={i}> <TableCell> {{docs.name} </TableCell> </TableRow> ))} </TableHead> I am looking for a wa ...

What is the process for using dojo to load content?

As I work on creating a single-page website with the help of dojo, I refer to tutorials that explain how to utilize dojo/request for ajax requests. The process is straightforward - simply make a request, receive HTML content, and insert it into a designate ...

Unlock the Potential of Azure Open Data With PHP

I am currently exploring the functionality of a webservice provided by RDW. This particular webservice allows users to retrieve information about a car by inputting its license plate number. Below is the link that I have been utilizing for this purpose. h ...

When the mouse hovers over it, show text instead of an icon on a React Material UI button

I'm currently working on a project that involves using material ui buttons. Initially, the add button only displays the + icon. Now, I want to change the button content from the icon to the text "CREATE ITEM" when the mouse is hovered over it. Check ...

Enhancing MongoDB query efficiency using Promise technology

At the moment, I am deeply involved in a personal project that is presenting a challenge with two different approaches to querying MongoDB. CustomerSchema.methods.GetOrders = function(){ return Promise.all( this.orders.map(orderId => Order. ...

Effects of incorporating unnecessary packages on Vue.js performance

In my Vue.js component, I have imported the module useI18n from "vue-i18n" but have not utilized it anywhere within the component. Concerned about how this could affect performance, particularly in terms of bundle size and load times. Will importing a mod ...

Utilizing AJAX for showcasing the data from an XML document

Our professor gave a brief explanation of AJAX, expecting us to showcase the data from an XML file in a scrollable text area on our website. Unfortunately, I am facing issues with loading the XML file into the designated div area. Any assistance or suggest ...

Saving JSON data as a file on server

Currently, I am running a localhost website on my Raspberry Pi using Apache and I am seeking advice on how to export a JSON string to a file on the Raspberry Pi itself. While I do know how to export a file, I am unsure of how to send it to the Raspberry Pi ...

Restrict the character count in Vue Material chips

Currently, I am utilizing the Vue Material Chips component to gather string arrays. My goal is to limit the character length of each string within the array to 30 characters. The component offers a md-limit prop which restricts the number of strings in th ...

I encountered an issue with my $.getJSON function in conjunction with PHP Post as it was returning a null value

I am facing an issue with executing a JSON query to a local file. The script I am using is as follows: <script> $('.Import').on('click', function(){ $.getJSON("charFetch.php?name=" + $('.charname').val() + "&rea ...

Despite making changes, the React Element continues to be rendered

I am a beginner in React and facing an issue with my simple app My aim is to implement a search functionality, but the problem arises when I search for an element - all search results are displayed After clearing the search box, all elements appear as in ...

Showing text in a textarea while maintaining formatting (such as using <br>)

Can someone help me with formatting a block of text like this: hello <br> how is your day <br> 123 To look like this: hello how is your day 123 I also need to display it in a textarea field. I attempted to do so using the following code: $ ...

Generate a revised object from a function and return it to the caller

What is the most efficient way to update and return a new object from a function? I came up with this function: export const addItemToCart = (currentCart, item) => { const { name, ...otherProps } = item; // if the item is already in the cart if ...