简体   繁体   中英

Can I add an image to a d3js graph?

Is it possible to add an image in the bottom right corner of my bar chart? I want to look something like this graph

graph.jpg

This is the link to the image I want to add. https://postimg.org/image/3zrzf3vpr/ Do I need to resize it before I connect it or can I do this within the code?

Here is my Plunker: http://plnkr.co/edit/sekJlYevx2dw28zLuC4d?p=preview

I assumed I could add it similar to how I add text using what I have below. Though if these is a better way to do it without basing it off the xaxis that would be fantastic.

svg.append("g")
  .attr("class", "x axis")
  .attr("transform", "translate(0," + height + ")")
  .call(xAxis)
  .append("text")
  .attr("class", "label")
  .attr("x", 170)
  .attr("y", 40)
  .style("text-anchor", "end")
  .text("Source: D.C. Open Data, D.C. Policy Center");

but I'm having a hard time figuring out the exact way to do it.

Putting the image in a separate element is one approach.

The better approach in my opinion is to have it inside your SVG. You can append it like the following and position it accordingly. I used the following to add it to your plunkr:

  var imgs = svg
        .append("svg:image")
        .attr("xlink:href", "https://s27.postimg.org/h3xjrsnrn/dcpolicycenter.png")
            .attr("x", width - 100)
            .attr("y", height - 14)
            .attr("width", "100")
            .attr("height", "100");

I've updated your Plunkr. Please check here -> http://plnkr.co/edit/hNZXJaKGwTu9Ps4VlhfJ?p=preview

您可以将图像(图形中的单独元素)放在图形下方,将图像的位置设置为绝对,并调整其属性(例如,顶部,左侧),使其位于您想要的位置。

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