D3 How to place image next to horizontal line text

可紊 提交于 2021-02-08 15:05:51

问题


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">

回答1:


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/



来源:https://stackoverflow.com/questions/40508241/d3-how-to-place-image-next-to-horizontal-line-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!