What is the best method for eliminating duplicate values within d3?

Is there a way to display only unique values in the legend for a scatterplot created in d3?

Another question I have is how can I remove commas from the axis labels?

To visualize this issue, here is the current look of the plot: https://i.sstatic.net/X1h0p.png

Shown below is the code snippet within the d3.csv function:

var x = d3.scaleLinear()
  .domain([1900,d3.extent(data, d=> d.yearFilmed)[1]])
  .range([0, width]);
svG
  .append('g')
  .attr("transform", "translate(0," + height + ")")
  .call(d3.axisBottom(x));

var y = d3.scaleLinear()
  .domain([1900,d3.extent(data, d=> d.yearBuilt)[1]])
  .range([height, 0]);
svG
  .append('g')
  .call(d3.axisLeft(y));


const colorScale = d3.scaleOrdinal()
  .range(d3.schemeCategory10);


var plot = (data, svG) =>{
var circle = svG.selectAll('circle')
    .data(data);
circle
    .enter()
    .append("circle")
    .attr("cx", function(d){ return x(d.yearFilmed) })
    .attr("cy", function(d){ return y(d.yearBuilt) })
    .attr("r", 10)
    .attr('fill', d => colorScale(d.filmGenre))
    .on("mouseover", tipMouseover)
    .on("mouseout", tipMouseout);    
var rekt = svG.selectAll("rect")
                .data(data)
                .attr("class", "legend");

rekt
    .enter()
    .append('rect')
    .attr("x", width+20)
    .attr("transform", function(d, i) { return "translate(0, " + i * 20 + ")"; })
    .attr("width", 18)
    .attr("height", 18)
    .attr("fill", d => colorScale(d.filmGenre));

svG.selectAll("text.legend")
rekt.enter()
    .append("text")
    .attr("class", "legend") // create a class for legend text. so when you make changes to it, other text on this pg won't be affected
    .attr("y", 15)
    .attr("x", width+45)
    .attr("transform", function(d, i) { return "translate(0, " + i * 20 + ")"; })
    .text(function(d) {return d.filmGenre;})

rekt
    .exit()
    .remove()
};
var archStyl = () => {
    d3.selectAll('rect')
    .attr("fill", d => colorScale(d.archStyle))
    d3.selectAll('text.legend')
    .text(function(d) {return d.archStyle;});
    d3.selectAll("circle")
    .transition()
    .attr('fill', d => colorScale(d.archStyle)); 
    plot(data, svG);
};
var filmGenr = () => {
    d3.selectAll('rect')
    .attr("fill", d => colorScale(d.filmGenre))
    d3.selectAll('text.legend')
    .text(function(d) {return d.filmGenre;});
    d3.selectAll("circle")
    .transition()
    .attr('fill', d => colorScale(d.filmGenre)); 
    plot(data, svG);
};

document.getElementById('archStyl').addEventListener('click', archStyl);
document.getElementById('filmGenr').addEventListener('click', filmGenr);

plot(data, svG);

});

Answer №1

Update your code using this snippet to extract only distinct values

const rectangles = svg.selectAll("rect")
           .data(d3.map(data, function(d){return d.filmGenre;}).keys())
           .attr("class", "legend");

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

Unlocking Extended Functionality in JQuery Plugins

At the moment, I am utilizing a JQuery Plugin known as Raty, among others. This particular plugin typically operates as follows: (function($){ $.fn.raty = function(settings, url){ // Default operations // Functions ...

Searching Firebase by using comparison operators on various fields

const FindFiis = async () => { const data: any[] = []; // Firebase query with inequalities on different fields to retrieve docs. // Objective: Select documents where dividendYield is between 8 and 20 and pvp is less than or equal to 1. ...

What is the process for adding content to a JSON object?

I may have a simple question, but I'm new to backend development and I'm trying to figure out how to post in JSON format. Here is the JSON schema I am working with: email: { type: String, unique: true, lowercase: true, required ...

Ensuring that the initial column of a table remains in place while scrolling horizontally

Thank you for taking the time to read this. I am currently working on a table within a div container (div0) where the data is dynamically generated, resulting in a table with unpredictable height and width. The outer div allows for both vertical and horizo ...

Whenever a query is entered, each letter creates a new individual page. What measures can be taken to avoid this?

Currently, I am working on a project that involves creating a search engine. However, I have encountered an issue where each time a user types a query, a new page is generated for every alphabet entered. For instance, typing 'fos' generates 3 pag ...

Place 4 divs within 2 divs, with one aligned to the left and the other to the right

I'm currently working on a small project using Angular 2 for an experiment, where I need to place 4 divs, each containing an image, within 2 divs. However, all the divs (with images) are stacked vertically instead of being placed next to each other, ...

Create an array using the array function in C++

Can C++ support a functionality like the following: uint8_t[] retrieveData() { uint8_t data[2] = {5, 2}; return data; } uint8_t dataArray[] = retrieveData(); ...

The Angular directive alters the scope, however, the template continues to display the unchanged value

I am working with a directive that looks like this: .directive('myDirective', function() { return { restrict: 'AE', replace: true, templateUrl: '/myDirective.html?v=' + window.buildNumber, ...

The EJS template in an Express.js (Node.js) application is not updating to show recent modifications

I'm currently developing a node.js application that serves an index.ejs page through a route named index.js. var express = require('express'); var router = express.Router(); /* GET home page. */ router.get('/', function(req, res) ...

What is the best way to implement a loop using JQuery?

<script> $(function() { $('.slideshow').each(function(index, element) { $(element).crossSlide({ sleep: 2, fade: 1 }, [ { src: 'picture' + (index + 1) + '.jpg' } ]); }); ...

JavaScript has a flaw in its date validation that allows for incorrect dates like 'dd.mm.0302' or '27.08.0974' to pass through

I have encountered an issue with date validation from the database where some years in the date fields appear to be incorrect (such as 28.02.0302). I need to validate these dates properly, but the functions I found online are not working as expected. How ...

What is the most effective method for retrieving a key and value from an Axios response object?

I currently have a Mongoose schema set up to store key:value pairs in a mixed type array, represented like this: Mongoose const budgetSchema = new Schema({ earnings: Number, expenses: [mongoose.Schema.Types.Mixed] }); budget:{ earning:1000, exp ...

What is the best way to assign a unique ID to every element in this situation?

Here is the given code: var words = ['ac', 'bd', 'bf', 'uy', 'ca']; document.getElementById("wordTable").innerHTML = arr2tbl(2); function arr2tbl(ncols) { return words.reduce((a, c, i) => { ...

Raphael JS Path Animation: Wiping Away

I have successfully created a line animation using RaphaelJS, which can be viewed on this jsfiddle link - http://jsfiddle.net/7n040zdu/. My next challenge is to create an erasing animation that follows the initial one. This erasing animation should mimic t ...

Unable to locate the specified script using node.js

Recently, I've started working with Javascript and Node.js. My current project is utilizing OpenMCT (https://github.com/nasa/openmct) and I'm facing an issue when trying to integrate a script as a plugin in an index.html file. Upon starting the N ...

Discovering the Voice Channel of a User using Discord.js v13

I'm currently working on a 'wake up' command for my bot that should move the mentioned member between 2 specific voice chats and then return them to their original VC. I've successfully got the bot to move me between those 2 VCs, but no ...

Algorithm for combining animation with a click event in JS/jQuery

I am currently working on a webpage that displays a simple div when the cursor is not hovering over it. When the cursor hovers over the div, it fades into a different div with unique content. The intention is for the simple div to remain non-clickable, wh ...

Tips for emphasizing a table row according to its value

I am currently developing a Google web application that involves CRUD data generated from Google Sheets. The search function is working perfectly, but I am trying to enhance it by highlighting specific rows based on the data value in Column 7. For example ...

What is the reason behind arr.reverse() flipping the original array?

My goal is to reverse an array and store the reversed version in a new array without altering the original array. Here is the code I am using: var arr= ["1", "2", "5"] var arrTwo = arr.reverse(); console.log(arrTwo) \\ ["5" , "2" , "1"] console. ...

Obtaining a compressed file via a specified route in an express API and react interface

Feeling completely bewildered at this point. I've had some wins and losses, but can't seem to get this to work. Essentially, I'm creating a zip file stored in a folder structure based on uploadRequestIds - all good so far. Still new to Node, ...