简体   繁体   中英

Append multiple 'text' elements in d3

I have a graph with an element which appears on mouseover, to which there is attached a circle, text and an svg:line as follows:

    var focus = svg.append("g")
        .attr("class", "focus")
        .style("display", "none")

    var circleRadius = 4.5;

    focus.append("circle")
        .attr("r", circleRadius);

    focus.append("text")
        .attr("y", -9)
        .attr("x", 0)
        .style("text-anchor", "middle");

    focus.append("svg:line")
        .attr("x1", 0).attr("x2", 0) // vertical line so same value on each
        .attr("y1", circleRadius).attr("y2", 200); // top to bottom 

    /*focus.append("text")
        .attr("y", -2)
        .attr("x", -20);*/

I want to add a second text element (the one currently commented out) but when I try to do that it won't render the first text element. Is there a way to append multiple elements of the same type to a group? Also I need to be able to select them independently (as shown below, I have two focus.select('text') functions, one for each text element, and currently I can't distinguish them).

Secondary question; the second text element is showing a time string in full format (eg Thu Jun 26 2014 08:30:00 GMT-0600 (Mountain Standard Time)). Can I format this on the fly to get just the hour/minute/seconds? Currently the text elements get data from this code:

        focus.select("text")
            .text(d.temperature)
            .attr("font-family", "NorWester")
            .attr("font-size", 11);
        focus.select("text")
            .text(d.time)
            .attr("y", function() { return (height - y(d.temperature)) })
            .attr("font-family", "NorWester")
            .attr("font-size", 11);

What SVG element is focus? I think it must be a g to work with multiple text elements.

For the formatting, d3 has a neat function:

var format = d3.time.format('%H:%M');
// ...
focus.select('text').text(function(d) {return format(d.time);});

Edit: Working jsfiddle demo, showing two texts elements inside a group: jsfiddle.net/PRvGC/

I had a similar issue recently when I wanted to create 4 rectangles with different properties. I solved this with HTML ids and selectAll. Here is an example:

var van = road.selectAll('#van').data([5]).enter() 
.append('rect')
.attr('x', function(d) { return 300})
.attr('y', function(d) { return 100})
.attr('width', 30)
.attr('height', 15)
.style('fill', 'brown');

Time formatting in D3: https://github.com/mbostock/d3/wiki/Time-Formatting

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM