Skip to content
Advertisement

How do I match up text labels in a legend created in d3

I am building a data visualization project utilizing the d3 library. I have created a legend and am trying to match up text labels with that legend.

To elaborate further, I have 10 rect objects created and colored per each line of my graph. I want text to appear adjacent to each rect object corresponding with the line’s color.

My Problem

-Right now, an array containing all words that correspond to each line appears adjacent to the top rect object. And that’s it.

I think it could be because I grouped my data using the d3.nest function. Also, I noticed only one text element is created in the HTML. Can anyone take a look and tell me what I’m doing wrong?

JS Code

JavaScript

Image of the problem: enter image description here

P.S. I cannot add a JSfiddle because I am hosting this page on a web server, as that is the only way chrome can read in my CSV containing the data.

My Temporary Solution

JavaScript

Advertisement

Answer

Problem

Your problem has to do with this code

JavaScript

You are appending only a single text element and in the text function you are returning the complete array of words, which is why all words are shown.

Solution

Create a corresponding text element for each legend rectangle and provide the correct word. There are multiple ways to go about it.

You could use foreignObject to append HTML inside your SVG, which is very helpful for text, but for single words, plain SVG might be enough.

I advise to use a g element for each legend item. This makes positioning a lot easier, as you only need to position the rectangle and text relative to the group, not to the whole chart.

Here is my example:

JavaScript

This should work as expected. Please note the use of groups for easier positioning.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement