D3.js: Exploring the beauty of layered legends

I have a question regarding creating legends with triangle shapes. Specifically, I am trying to create two triangles representing "Yes" and "No". However, when I run the code below, the triangles end up overlapping each other. In an attempt to separate them, I included the line of code

.attr("y", function(d,i) {return 50+i*40;})
, but it doesn't seem to be working. Could someone please advise me on how to resolve this issue? Thank you! Click here! This is an html screenshot for reference

  var legendname = ["Yes","No"];   
     var legend = svg.selectAll(".legend")
              .data(legendname)
              .enter().append("g")
              .attr("class", "legend")
               .attr("transform", function(d, i) {
            return "translate(" + (w + 150) + "," + (m.t - 30) + ")";
          });

          legend.append("path")
              .attr("d", d3.svg.symbol().type("triangle-up").size(128))
             ***  .attr("y", function(d,i) {return 50+i*40;})
               .style('fill', function(d) {return color(d);});

             legend.append("text")
               .attr("y", function(d,i) {return 50+i*20;})
               .attr("x", 30)
               .text(function(d) { return d; })

Answer №1

To update the translate y attribute of groups instead of paths, you won't need additional calculations for the y attributes of texts and paths.

.attr("transform", function(d, i) {
        return "translate(" + (w + 150) + "," + (30+i*40) + ")";
 });

Effective Code Snippet:

var w=40; //Setting sample chart width
 var color = d3.scale.category20c();
var svg = d3.select("body").append("svg").attr({ height: 500, width: 400 });

var legendname = ["Yes", "No"];
var legend = svg.selectAll(".legend")
  .data(legendname)
  .enter().append("g")
  .attr("class", "legend")
  .attr("transform", function(d, i) {
    return "translate(" + (w + 150) + "," + (30+i*40) + ")";
  });

legend.append("path")
  .attr("d", d3.svg.symbol().type("triangle-up").size(128))
  .style('fill', function(d,i) {
    return color(i);
  });

legend.append("text")
   .attr("dx",10)
   .attr("dy",".4em")
  .text(function(d) {
    return d;
  })
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

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

``Why is my setFeatureState function not updating the value in my Mapbox map

I've been attempting to change the stroke of a circle upon clicking it on mapbox. Despite following mapbox's documentation, the values don't seem to update. The console is also clear. t.map.addLayer({ id: id, type: 'circle&apo ...

The error message "Required parameter not provided" appeared when trying to utilize a nested dynamic route in Next.js

Issue: The error message indicates that the required parameter (plantName) was not provided as a string in getStaticPaths for /plants/[plantName]/streaming-data/[panel] The error above is being displayed. My folder structure follows this pattern: plants > ...

Echarts: scatter plots linked with a line to the axis (resembling the PACF diagram)

I am currently working with echarts (js). Is there a method to link the dot of the scatter plot with the 0 value on the y-axis? I want it to resemble a pacf plot, similar to this example: The desired outcome should look something like this: https://i.sta ...

Press the second form submit button after the completion of another Observable

Below is the unique process we aim to accomplish using solely RXJS Observables: Press Login button (form with username & password). We bind Observable.fromEvent with our form. Upon submitting the form, call loginUser() to send an http request to serv ...

Different conversations are taking place concurrently. How can we determine which one is currently being attended to

In my application, multiple dialogs are open simultaneously, each with its own set of shortcuts. It is important to ensure that these shortcuts work correctly based on the focused dialog. Is there a way to determine which dialog is currently in focus? Ed ...

Angular factory transforming service

I am looking to transform the 'i18n' function into a factory in order to return a value instead of just setting it. Any suggestions or tips would be greatly appreciated! services.factory('i18nFactory', function() { var language = ...

SoundCloud and Vimeo have the capability to link their players across separate tabs, and even between tabs and embedded players

I find it intriguing how SoundCloud and Vimeo are synchronized with their tabs, so that when you play something in one tab, the others pause. It's worth noting that this feature only works on SoundCloud when two instances of the website are open, wher ...

Deleting lines from JSON object using Angular or JavaScript

On my webpage, I have a list where you can add a new line by pressing the "+" button (easy with push), but I'm not sure how to remove lines using the "X" button. https://i.stack.imgur.com/nm06A.png This is the JSON structure: "priceExtra" : [ ...

Transform the object into JSON while excluding specific (private) attributes

I recently started using dean edwards base.js for organizing my program into objects. I must say, base.js is truly amazing! But now I have a question that doesn't require prior knowledge of base.js to answer. Within one of my objects, I have a proper ...

Determine the validity of an image URL using Vue.js

Is there a way to check if an image URL is valid or broken in Vue.js, similar to the process outlined in Angular 2 - Check if image url is valid or broken? ...

Converting a timestamp from PHP in JSON format to date and time using JavaScript

Within the JSON file, there is a timestamp associated with each user login. An example of this timestamp is: timestamp: "1541404800" What steps should be taken to convert this timestamp into date and time format? ...

Choose an option using jQuery with the ability to navigate to the previous or next

I encountered a bug when I tried to click the next or previous button. Below is the HTML code snippet: $("#nextPage").click(function() { $('#pagination option:selected').next().attr('selected', 'selected'); console.log( ...

Ways to filter and display multiple table data retrieved from an API based on checkbox selection in Angular 2 or JavaScript

Here is a demonstration of Redbus, where bus data appears after clicking various checkboxes. I am looking to implement a similar filter in Angular 2. In my scenario, the data is fetched from an API and stored in multiple table formats. I require the abili ...

What is the best way to convert an Angular object into a string using a for-loop and display it using $sce in AngularJS?

Currently, I am rendering a block of HTML and directives using $sce.trustAsHtml. To achieve this, I utilized a directive called compile-template which enables the use of ng-directives like ng-click and ng-disabled. While it is possible for me to pass sta ...

Interconnected realms communication

I'm currently in the process of developing a Facebook iframe app. At one point, I initiate a friends dialog from Facebook and embed an HTML button to add some customized functionality for my app. dialog = FB.ui({ method:'fbml.di ...

Is it okay to incorporate this code into the existing plugin?

My plugin, known as "pluggable," has the ability to take any element with the class .plugin and inject the following markup into it: <span class="colorable">color me</span> Below is the original markup containing elements with the class "plug ...

Converting a string array to an array object in JavaScript: A step-by-step guide

My task involves extracting an array from a string and manipulating its objects. var arrayString = "[{'name': 'Ruwaida Abdo'}, {'name': 'Najlaa Saadi'}]"; This scenario arises when working with a JSON file where ce ...

Issue with Nextjs environmental variables not functioning in JavaScript pages

Currently, I am in the process of developing a Next.js website. Within my JavaScript file, I am fetching data from an API and assigning a token using the .env.local file. However, when attempting to access the .env variable that I've set up, it seems ...

Displaying a loading screen while a jQuery ajax request is in progress

Currently, I am attempting to display a loading div while waiting for an ajax call to finish. Despite experimenting with various methods, I have not been able to consistently achieve the desired outcome. In my present code, everything functions properly o ...

Conditional jQuery actions based on the selected radio button - utilizing if/else statements

This task seemed simple at first, but I quickly realized it's more challenging than expected. Apologies in advance, as Javascript is not my strong suit. My goal is to have the main button (Get Your New Rate) perform different actions based on whether ...