d3轴标签

如何在d3中向轴添加文本标签?

例如,我有一个简单的线图与x和y轴。

在我的x轴上,我有从1到10的滴答。我希望单词“天”出现在它下面,以便人们知道x轴正在计算天数。

同样,在Y轴上,我有数字1-10作为蜱虫,我想要“吃三明治”的话出现在侧面。

有一个简单的方法来做到这一点?

轴标签不是内置于D3的轴组件 ,但您可以通过添加SVG text元素来添加标签。 一个很好的例子就是我对Gapminder的animation泡沫图,国家的财富与健康的娱乐。 x轴标签看起来像这样:

 svg.append("text") .attr("class", "x label") .attr("text-anchor", "end") .attr("x", width) .attr("y", height - 6) .text("income per capita, inflation-adjusted (dollars)"); 

而y轴标签是这样的:

 svg.append("text") .attr("class", "y label") .attr("text-anchor", "end") .attr("y", 6) .attr("dy", ".75em") .attr("transform", "rotate(-90)") .text("life expectancy (years)"); 

您也可以使用样式表对这些标签进行样式设置,或者一起( .y.label ),或者单独使用( .x.label.y.label )。

在新的D3js版本(版本3以上)中,当通过d3.svg.axis()函数创build图表轴时,您可以访问函数内部的两个名为tickValuestickFormat的内置方法,以便您可以指定值,你需要的刻度和以什么格式,你想文本显示:

 var formatAxis = d3.format(" 0"); var axis = d3.svg.axis() .scale(xScale) .tickFormat(formatAxis) .ticks(3) .tickValues([100, 200, 300]) //specify an array here for values .orient("bottom"); 

如果你想像我这样在y轴中间的y轴标签:

  1. 旋转文字90度与文字锚中间
  2. 将文本翻译为中点
    • x位置:防止y轴刻度标签重叠( -50
    • y位置:匹配y轴的中点( chartHeight / 2

代码示例:

 var axisLabelX = -50; var axisLabelY = chartHeight / 2; chartArea .append('g') .attr('transform', 'translate(' + axisLabelX + ', ' + axisLabelY + ')') .append('text') .attr('text-anchor', 'middle') .attr('transform', 'rotate(-90)') .text('Y Axis Label') ; 

这样可以防止上面提到的lubar旋转整个坐标系。

D3提供了一个相当低级的一组组件,可以用来组装图表。 给出构build模块,轴组件,数据连接,select和SVG。 这是你的工作,把它们放在一起形成一个图表!

如果你想要一个传统的图表,即一对轴,轴标签,图表标题和绘图区,为什么不看看d3fc ? 它是一个更高级的D3组件的开源集合。 它包含一个笛卡尔图表组件,可能是您所需要的:

 var chart = fc.chartSvgCartesian( d3.scaleLinear(), d3.scaleLinear() ) .xLabel('Value') .yLabel('Sine / Cosine') .chartLabel('Sine and Cosine') .yDomain(yExtent(data)) .xDomain(xExtent(data)) .plotArea(multi); // render d3.select('#sine') .datum(data) .call(chart); 

你可以在这里看到一个更完整的例子: https : //d3fc.io/examples/simple/index.html

如果您按照build议在d3.v4中工作,则可以使用此实例提供您所需的一切。

您可能只想用“天”来replaceX轴数据,但请记住正确parsingstring值,而不应用连接。

parseTime不如做date格式的日子缩放的技巧?

 d3.json("data.json", function(error, data) { if (error) throw error; data.forEach(function(d) { d.year = parseTime(d.year); d.value = +d.value; }); x.domain(d3.extent(data, function(d) { return d.year; })); y.domain([d3.min(data, function(d) { return d.value; }) / 1.005, d3.max(data, function(d) { return d.value; }) * 1.005]); g.append("g") .attr("class", "axis axis--x") .attr("transform", "translate(0," + height + ")") .call(d3.axisBottom(x)); g.append("g") .attr("class", "axis axis--y") .call(d3.axisLeft(y).ticks(6).tickFormat(function(d) { return parseInt(d / 1000) + "k"; })) .append("text") .attr("class", "axis-title") .attr("transform", "rotate(-90)") .attr("y", 6) .attr("dy", ".71em") .style("text-anchor", "end") .attr("fill", "#5D6971") .text("Population)"); 

摆弄全球css / js