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

Injecting services differently in specific scenarios in AngularJS

I have a unique angular service called $superService that I utilize across many of my directives and controllers. However, there is one specific directive where I want to implement the following behavior: If another directive utilizes $superService in its ...

The 'npm start' command is failing to recognize the changes made to the

I am embarking on a new node application journey, starting with the package.json below, which is quite basic. { "name": "mynewnodeventure", "version": "1.0.1", "description": "Exploring node", "main": "index.js", "start": "node server. ...

Disabling $routeprovider while implementing bootstrap

I am encountering an issue with my normal routeprovider code. In a specific section of my HTML, I have some Twitter Bootstrap expand/collapse sections which inadvertently trigger the routeprovider when clicked. Is there a way to prevent this from happening ...

Determine if a specific checkbox with a particular id has been selected using JQuery

Looking for assistance on how to determine if a checkbox with a specific ID is checked or unchecked. <input name="A" id="test" type="checkbox" value="A" /> <input name="B" id="test" type="checkbox" value="B" /> <input name="C" id="test1" t ...

Utilizing Asynchronous Functions within a Loop

I have a situation where I am working with an array and need to make API calls for each index of the array. Once the API call is resolved, I need to append the result in that specific element. My goal is to ultimately return the updated array once this pro ...

What is the best way to prevent certain search terms from appearing in search results on my website's search form

Is there a way to prevent certain search terms from showing up in my search box? For example, how can I block the search query for "dog"? <form id="headbar-search" action="search.php" method="GET" x-webkit-speech="x-webkit-speech"> <input type="t ...

Transform your HTML audio player into a Vue component

I am in the process of converting an HTML player into a Vue component. Half of the component has been successfully converted, but the time control slider is still missing. Below is the original HTML code for the player: // JavaScript code for the audi ...

What is the process of converting TypeScript to JavaScript in Angular 2?

Currently diving into the world of Angular 2 with TypeScript, finding it incredibly intriguing yet also a bit perplexing. The challenge lies in grasping how the code we write in TypeScript translates to ECMAScript when executed. I've come across ment ...

Does the PHP include function act as an HTTP request?

After coming across an article highlighting the negative impact of using excessive HTTP requests on server speed, I started wondering about the performance implications of PHP includes. Specifically, I'm curious if sending 4 AJAX requests compared to ...

ProgressMeterJS Plugin - Full-width Progress Bar

I have encountered a question regarding this particular plugin found at: My goal is to adjust the progress bar's width to 100% so it matches the width of its container. So far, I have made modifications to the plugin by changing the following line: ...

retrieveSourceData(), postmodification of Handsontable with Vue

How can I use getSourceData() after a change event in Vue? I need to access the instance of Handsontable, but I'm not sure how to do that in Vue. Essentially, I need to retrieve all rows that have been edited. For example: const my_instance = this.$ ...

"Image Reactor: Unleashing the Power

I'm struggling to understand why my relative path image loading isn't functioning correctly. The assets are located within the src folder in my working directory, but for some reason, they're not displaying as expected. When I directly impo ...

What is the best way to reach nested iframes?

I am looking for a solution to send post messages (window.postmessage) to iframes. Currently, it is functioning properly with a single iframe inside the parent page. However, I want it to also work for nested iframes. Here are the criteria: I should on ...

Using JavaScript's regular expressions to identify a code block that commences with a specified pattern

Currently, I am working on a JavaScript script and I am in need of a Regex pattern to quickly match "JSDocs". The specific pattern that I am trying to match looks like this: # this is block1 /// text /// text /// text /// text # this is block2 /// text // ...

Endless [React Native] onFlatList onEndReached callback invoked

Attempting to create my debut app using ReactNative with Expo, I've hit a snag with FlatList. The components are making infinite calls even when I'm not at the end of the view. Another issue might be related; across multiple screens, the infinite ...

Updating ng-model with the values from a property in a collection in AngularJS

Encountering an unusual problem with setting the ng-model for a select drop-down menu. Despite using a property value that matches one in the ng-options, the ng-model consistently ends up as null. Below is the function responsible for fetching orders: o ...

The latest update to the Server Stats code mistakenly changes the channel to "undefined" instead of displaying the total number

I've been working on a private bot for a specific server that displays server statistics and more. However, I've encountered an issue where every time a user joins or leaves the guild, the bot updates a channel with 'undefined' instead ...

Pattern for identifying text that exclusively consists of whitespace characters and `<br>` tags

Here is an example of a string: <br /> <br /> <br /> Sometimes the string can look like this: <br /> <br /> Or simply like this: & ...

The reason why Express is not directing to the static React build files is due to the absence of a specific URL slug

The Scenario Currently, I'm in the process of developing a React application that is being served statically through Express. To clarify, the React app is constructed using npm run build and the resulting static files are stored within the build/ ...

Attempting to abbreviate repetitive Javascript instructions

I have this functional javascript code, but I feel like there might be a more efficient way to write it. Any suggestions on simplifying this? let searchTerm = 'Some search text'; const isMatch = entry.title.toLowerCase().includes(searchTer ...