首页 > 解决方案 > 当我向我的 svg 添加标题和副标题时,它们会出现在我的图形上方

问题描述

我基本上有一个条形图,我想放 2 个文本。我想在离我的图表一定距离的地方放置一个标题(例如前 30px)。我想在离图表一定距离的地方放置一个字幕,使其位于右下角(例如底部 30px)

在此处输入图像描述

无论我使用什么方法,我的文本总是在我的图形之上,我希望我在图形和文本之间有分隔边距。

想要的效果:

在此处输入图像描述

我究竟做错了什么?

这是我的实时代码:

https://plnkr.co/edit/mRjyYN9nWiMWYRzj7Gtf?p=preview

var svg = d3.select("body").append("svg")
  .attr("width", width + margin.left + margin.right)
  .attr("height", height + margin.top + margin.bottom)
  .append("g")
  .attr("transform",
    "translate(" + margin.left + "," + margin.top + ")");


//set title
svg.append("text")
  .attr("x", (width / 2))
  .attr("y", 0 - (margin.top / 2))
  .attr("text-anchor", "middle")
  .style("font-size", "18px")
  .text("title");


//set bottom-right text

svg.append("text")
  .attr("x", 960 - 80)
  .attr("y", 500 - 30)
  .attr("text-anchor", "middle")
  .style("font-size", "14px")
  .text("subtitle");

使用您的代码的当前问题(用户 lemming):

在此处输入图像描述

标签: javascriptd3.js

解决方案


通常,您从要渲染到的 div 的尺寸中减去边距,就像这样,假设 div 是 800 x 600

// set the dimensions and margins of the graph
var margin = {top: 10, right: 30, bottom: 30, left: 50},
    width = 800 - margin.left - margin.right,
    height = 600 - margin.top - margin.bottom;

那有意义吗?


推荐阅读