Generating numerous circular elements for each item in the dataset using D3

My dataset consists of various years and corresponding numerical values for each year as shown below:

    "data":[
            ["1951","306","27","159","34","82","4"],
            ["1956","426","41","203","47","119","16"],
            ["1959","562","67","267","48","148","32"],
            ["1960","605","76","282","54","157","36"],
            ["1961","665","88","310","57","168","42"],
            ["1962","749","116","340","60","189","44"],
            ["1963","847","140","375","63","215","54"],
            ...

The first element in each sub-array represents the year. I have set up two coordinate axes based on this data. Now, I am looking to create 6 circle elements for each of these entries. How can I achieve this by modifying the given code snippet?

var circles = svg.selectAll("circle")
                .data(data.data)
                .enter()
                .append("circle");

var circleAttr = circles. //Attributes defined here

Answer №1

To achieve the desired outcome, you can apply the

.selectAll(...).data(...).enter(...).append(...)
pattern consecutively by passing a function to the .data method during the second and subsequent iterations. This function will accept data from the previous level and produce an array of data items for that specific level.

Below is a simple example utilizing your dataset:

var colors = d3.scale.category10().domain([2000, 2010]);

var data = [
  ["2001", "100", "20", "50", "30"],
  ["2005", "150", "25", "70", "45"],
  ["2008", "200", "35", "90", "60"],
];

d3.select("body")
  .append("svg")
  .attr("width", 800)
  .attr("height", 600)
  .selectAll("g")
  .data(data)
  .enter()
  .append("g")
  .selectAll("circle")
  .data(function(d) {
    var year = +d[0];
    return d.slice(1).map(function(value) {
      return {
        year: year,
        value: +value
      };
    });
  })
  .enter()
  .append("circle")
  .attr("r", 4)
  .attr("cx", function(d) {
    return d.value;
  })
  .attr("cy", function(d) {
    return d.value;
  })
  .attr("fill", function(d) {
    return colors(d.year);
  });

Example: https://example.com/

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

Error message: AngularJS Jasmine spyOn: number has no functionality

I am encountering difficulties while attempting to execute a test that utilizes a mockup for a service call (retrieving location data from a web SQL database). Below is the controller code: .controller('LocationDetailCtrl', function ($scope, $s ...

Is there a way to continuously send out this ajax request?

My attempt to use setInterval for sending an AJAX request every 2 seconds is causing the page to crash. It seems like there is something wrong in my code! Check out the code below: var fburl = "http://graph.facebook.com/http://xzenweb.co.uk?callback=?" ...

Combining two JSON objects in JavaScript is simple when their IDs correspond to each other in both objects

I have a query related to merging two different objects from the database, both in JSON format. These two objects share two key/value pairs: IRBId = ... and id = ..., which can be seen in the examples below: OBJ 1 { "data":{ "IRBs":{ "n ...

In the year 2021, eliminate linked documents using mongoose/MongoDB middleware

After extensive research on stack overflow, I attempted various solutions for deleting referenced documents in MongoDB using node.js. Unfortunately, most of them either utilize deprecated methods or simply do not function as expected. Within my applicatio ...

What are some ways to enhance the opacity of a Material UI backdrop?

I'm looking to enhance the darkness of the material UI backdrop as its default appearance is not very dark. My goal is to make it dimmer and closer to black in color. ...

Anticipated a task or procedure but encountered an expression instead

I'm encountering an issue with the following code snippet. JShint is flagging it with "Expected an assignment or function and instead saw an expression". function checkVal(inputField) { ( inputField.val() === '' ) ? inputField.prev( ...

Parse JSON files from a folder and concatenate them to a CSV using Node.js

Thank you for offering your help. I have a collection of JSON files located in a directory with unknown names. I need help with the following: (1) Reading all the JSON files (2) Appending the data from the JSON files to output.csv (3) Adding "-Appended" t ...

Creating a Next.js dynamic route that takes in a user-submitted URL for customization

Currently, I have implemented the Next.js Router to facilitate the display of different dashboards based on the URL slug. While this functionality works seamlessly when a button with the corresponding link is clicked (as the information is passed to the Ne ...

Transmit a data point from JavaScript to PHP

I am looking to transfer the address value to a different PHP page <script> var userAddress = place.formatted_address; document.getElementById('af').innerHTML = userAddress; </script> ...

Accessing information from RESTful Web Service with Angular 2's Http functionality

I am currently working on retrieving data from a RESTful web service using Angular 2 Http. Initially, I inject the service into the constructor of the client component class: constructor (private _myService: MyService, private route: Activat ...

Effortlessly sending multiple values from text fields using jQuery

i am using jQuery to fetch all values from text fields with the same field name. $('input[name^="StudentName"]').each(function() { StudentName += $(this).val(); alert(StudentName); }); when I alert, all the values are displayed as one s ...

What is the best way to customize Node.js configuration when it is executed through npm?

Check out this documentation on node config: node myapp.js --NODE_CONFIG='{"Customer":{"dbConfig":{"host":"customerdb.prod"}}}' However, if I run a npm script, all parameters will be passed to npm instead of nodejs, right? How can I pass the -- ...

What is the best way to incorporate template literals (` `) into existing template literals?

I am facing a unique challenge where I need to utilize a template literal within another template literal, but I am struggling to make it work. The code snippet in question looks like this: <p>Something something <a href={`${SOMELINK}/blah`}> ...

What is the best way to create a smooth sliding effect using CSS?

Need help with creating a transition effect within a bordered div that reveals hidden content when a button is clicked? I'm looking to have the <a> tag displayed after clicking the button, with both the button and text sliding to the left. Here& ...

Uncovering components generated by React JS with BeautifulSoup

My goal is to extract anchor links with the class "_1UoZlX" from the search results on a specific page - After analyzing the page, I realized that the search results are dynamically generated by React JS and not readily available in the page source or HTM ...

The declaration file for the module 'bootstrap/dist/js/bootstrap' could not be located

Currently, I am developing a Next.js application and have integrated Bootstrap for styling. However, I am encountering an error when trying to import the bootstrap.bundle.js file. I am facing the following error message: Could not find a declaration file f ...

Converting an HTML ul-li structure into a JavaScript object: Steps to save the structure

My HTML structure uses ul and li elements as shown below: <ul class="treeview" id="productTree"> <li class="collapsable lastCollapsable"> <div class="hitarea collapsable-hitarea lastCollapsable-hitarea"></div> <span ...

Opposite path matching with Next.js middleware

For my Next.js project, I have implemented a middleware and now I need it to only apply to routes that do not start with /api/. I have checked the documentation but couldn't find a similar example. Is there a way to achieve this without manually excl ...

Tips for building a versatile client-server application with separate codebases for the JavaScript components

We are embarking on the process of rebuilding our CMS and leveraging our expertise with VueJS. Despite our familiarity with VueJS, we won't be able to create a full single-page application due to the presence of server-side rendering files (JSP). The ...

Understanding Java and JavaScript variables within a JSP webpage

I am currently working on populating a pie chart from Google with data fetched from my database. Although I have successfully retrieved the desired results in my result set, I am facing challenges in converting my Java variables into JavaScript variables ...