Garrett Garrett - 1 year ago 48
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?


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

<img src="" alt="Smiley face" height="42" width="42">

<img src="" alt="Sad face" height="42" width="42">

Answer Source

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

    .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 ? 
            "" :

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:

EDIT To display the images next to the ticks, not to the bars, change the x and y accordingly. This is the fiddle:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download