D3如何将图像放置在水平线文本旁边 [英] D3 How to place image next to horizontal line text

查看:33
本文介绍了D3如何将图像放置在水平线文本旁边的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了这个D3图表,该图表显示了结果情感值.但是,我正在努力做的是将图像放置在水平文本旁边.以JSFiddle为例,假设结果2"低于20%.结果2"文本的右侧将显示一张悲伤的脸.然后,如果该值大于20%,则会显示一张笑脸.可以这样做吗?

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

推荐答案

您可以使用三元运算符来定义要添加到小节旁边的图像:

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"
    });

因此,如果 d.value 小于20(true),它将附加第一个链接,否则(false)它将附加第二个链接.

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

这是您更新的小提琴: https://jsfiddle.net/c3k8c3a4/

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

编辑要在 ticks 旁边而不是在条形图上显示图像,请更改 x y 相应地.这是小提琴: https://jsfiddle.net/6uasj8hz/

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/

这篇关于D3如何将图像放置在水平线文本旁边的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆