Slava32
Slava32

Reputation: 171

How to set one label to the entire line of a graphic

I want to display, only once, a value that repeats on each step of a line graphic and set its position to the end of the line.

Supposing that value-column 3 (name of the column is "target", but can be any) in my data will always have the same value for every object, I want to label line "target" with its values (to display 25) only one time at the end of the line.

Here is the working_code and below is the piece of code which creates points on the lines and text values above these points:

// points on the lines
point.selectAll("circle")
    .data(function(d,i){ return d.values; })
    .enter().append("circle") 
    .attr("cx", function(d) { 
        return x(d.date);
      })
     .attr("cy", function(d, i) { return y(d.value); })
     .attr("r", 3) 
     .style("fill", function(d) { return color(d.name); });

// values above the points
var val = column.append("g")
    .attr("class","valori");

    val.selectAll("text")
    .data(function(d){ return d.values; })
    .enter().append("text")
    .attr("x", function(d) {
        return x(d.date);
        })
    .attr("y", function(d) { return y(d.value); })
    .attr('dy', -10)
    .attr("text-anchor", "middle")
    .text(function(d) { return d.value; }); 

I'm using slightly changed example of https://bl.ocks.org/mbostock/3884955

Any idea how to do that?

Thanks in advance!

Upvotes: 1

Views: 60

Answers (1)

Marcel Kohls
Marcel Kohls

Reputation: 1863

@Slava32, after the graph is displayed you can check the content of each line with JQuery and define who will be displayed or who will be hidded. I made a simple example of how you can do it: https://jsfiddle.net/MarcelKohls/rpevzsu8/

$( document ).ready(function() {
    var contentLines = $('.valori');

    $.each( contentLines, function( lkey, lvalue ) {
        var contentColumns = $(lvalue)[0];
        var totalColumns = $(contentColumns).find('text').length;
        var lastValue = $(contentColumns[0]).html();
        var totalRepeat = 1;

       $.each( $(contentColumns).find('text'), function( ckey, cvalue ) {
            if ($(cvalue).html() == lastValue){
            totalRepeat++;
         }

        lastValue = $(cvalue).html();
      });

      if (totalRepeat == totalColumns){     
        $(contentColumns).find(':not(:last)').hide();
      }
    });
}); 

I put the function on the onready event, but you can set it to do the process right after the graphic is set.

Upvotes: 1

Related Questions