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

The charts created using chartjs-vue display no data

After following some examples to create a test chart, I am facing an issue where the chart renders blank with dummy data. My initial suspicion is that maybe the options are not being passed for the lines, but it seems like dataCollection is not being popu ...

The fade-in effect will initiate from the start once the mouse leaves the element (with a

Currently, I am in search of a solution for improving the navigation menu I am developing. By clicking on this JSFiddle link, you can view the code in action. The issue I am facing is that the fadeIn effect should only occur when hovering over the nav-ite ...

Guide to executing two child processes sequentially in Node JS

I am working on two processes within a function: one generates a JSON file from an audio while the other normalizes the generated JSON file. However, I'm facing an issue where only one of the processes runs at a time - when the first one runs, the se ...

Issue with ng-grid in AngularJS: Data does not appear after resizing columns

Currently, I am encountering a problem where ng-grid data is not being displayed when column resizing occurs after changing the column names. To demonstrate this issue, I have created a plunkr at - http://plnkr.co/edit/eV9baoDOV9A46FZmKW8G?p=preview I wo ...

Exploring the Dev Tools Console feature in Excel for Windows

I have developed an Excel add-in using AngularJS. I utilize <div ng-show="isLoggedIn">...</div> and <div ng-show="!isLoggedIn">...</div> to manage different content based on the value of $scope.isLoggedIn. While it functions well i ...

Substitute empty spaces and organize the text layout

I'm struggling to figure out how to substitute the whiteSpace in an aggregate request using MongoDB and also how to remove a specific part of a string (most likely requiring regex). Here's an example of my document: { "_id": "57dfa5c9xxd76b ...

Simulate a click event on an element generated with JavaScript to initiate the download of a CSV file

I am attempting to generate an HTML element and trigger a click event in order to download a CSV file upon receiving an ajax response (the data array provided is for testing purposes only). $(document).on('click','.csv',function(){ ...

Implementing Various Conditions in ng-if Using AngularJS

I have a scenario in my AngularJS application where I need to display different buttons based on the value of type. If type === 'await_otp', then I should display two buttons (resend OTP and cancel), if type === 'submitted', then only t ...

How can I fetch a value from a database and set it as the selected option in a

I am facing an issue with the usage of the selectpicker plugin from Bootstrap in order to select multiple items. My requirement is to create a modal for editing where the data is fetched from previous records, particularly an array. I am looking for a way ...

Avoid connecting HTML input elements with both JavaScript and Java models

I am troubleshooting an issue with my login page code. <div ng-show="!loggedIn()"> <form ng-submit="login()"> Username: <input type="text" ng-model="userName"/> Password: <input ...

Guide to incorporating JavaScript libraries from NPM into a child theme built on Understrap

I am looking to incorporate the Chart Js library within my custom Understrap Child Theme. Instead of simply using a CDN script, which could potentially slow down load times or cause errors if the CDN is not accessible, I have opted to import it into my pac ...

Notify the chat when a new record is added to the database

Alright, so here's the issue I'm facing. I created a chat application using PHP and MySQL, but I noticed that when I enter text, it doesn't update in the other window automatically. This led me to experiment with iframes, which I found much ...

Dynamically load modules within an AngularJS application

Is there a way to dynamically load module scripts? I have 2 JS files: module1.js (function() { var mod = angular.module('module1', []); .... })(); This is the second one: module2.js (function() { var mod = angular.module('m ...

Exploring the concept of type identification in interpreted dynamic languages

How do dynamic scripting languages like Python, PHP, and JavaScript determine the datatype of a variable? /* C code */ int a = 1; int b = 2; int c = a * b; In the above C example, the compiler recognizes that 'a' and 'b' are integers. ...

Preventing template rendering in Angular until an event is triggered - but how?

I am currently working on a directive that functions well, but I had to resort to using inline template code in order to delay rendering until the click event occurs. However, I believe it would be more streamlined if I could assign the directive template ...

The issue with displaying inline block is that the divs are not appearing side by side on the

Two of my div elements, namely form-panel and data-panel, are currently not aligned on the same line. How can I use display:inline-block to align them in a single line? Please review the code provided below. I have already used display:inline-block on both ...

Improving React Efficiency: Should You Utilize Memoization of Axios GET Request Using useMemo or useCallback?

My Objective: I am currently working on a sizable function named getUnitedStatesCases, which involves making an Axios GET Request and performing various operations with the received data. I have already implemented it within a useEffect hook upon componen ...

Adjusting the sound levels of an HTML audio element using JavaScript

I'm looking to adjust the volume of an <audio> element when a user clicks on an image. HTML: <div id="cloud"> <img name="jsVolumeButton" src="images/cloud.png" width = "140px"/> </div> <audio id="player" src="sounds/rain. ...

employing the d3.queue method to defer execution until receiving the AJAX response

Seeking examples of integrating AJAX, d3, and PHP to extract data from a database and create graphs. Any guidance would be appreciated. I am currently using d3 to generate a force chart based on database information retrieved through AJAX and PHP. I have ...

When attempting to start a new React Native project using npx, I encountered an error stating "react-native: command not found"

After running 'npx react-native init MyProject' for the first time, it prompted that react-native would be downloaded, but I mistakenly terminated the process. Now, when I try again, it shows an error saying 'react-native: command not found& ...