Garrett Garrett - 28 days ago 5
CSS Question

D3 How to place image next to horizontal line text

I've created this D3 chart which displays the results sentiment value. However what I'm struggling to do is place an image next to the horizontal text. Using the JSFiddle as an example, lets say 'Result 2' is under 20%. There would be a sad face displayed to the right of the 'Result 2' text. Then if the value was higher than 20%... a happy face would be displayed instead. Is it possible to do this?

JSFiddle: https://jsfiddle.net/sopjzwst/3/

I've created the 2 different faces below the chart like so:

<img src="http://www.clipartkid.com/images/15/cartoons-cartoon-logos-cartoon-logo-design-gHlQ6b-clipart.jpg" alt="Smiley face" height="42" width="42">

<img src="http://www.clipartbest.com/cliparts/Rid/8EG/Rid8EGpi9.png" alt="Sad face" height="42" width="42">

Answer

You can use a ternary operator to define what's the image to append next to the bars:

svg.selectAll(".images")
    .data(data)
    .enter()
    .append("svg:image")
    .attr("x", function(d) {return x(d.value) + 4; } )
    .attr("y", function(d) { return y(d.sentiment) + 10; })
    .attr("width", 42)
    .attr("height", 42)
    .attr("xlink:href", function(d){
            return d.value < 20 ? 
            "http://www.clipartbest.com/cliparts/Rid/8EG/Rid8EGpi9.png" :
            "http://www.clipartkid.com/images/15/cartoons-cartoon-logos-cartoon-logo-design-gHlQ6b-clipart.jpg"
    });

So, if d.value is less than 20 (true), it appends the first link, otherwise (false) it appends the second link.

Here is your updated fiddle: https://jsfiddle.net/c3k8c3a4/

EDIT To display the images next to the ticks, not to the bars, change the x and y accordingly. This is the fiddle: https://jsfiddle.net/6uasj8hz/