本文介绍了d3轴标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do I add text labels to axes in d3?

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

For instance, I have a simple line graph with an x and y axis.

在我的x轴上,我有从1到10的刻度。我想要天一词出现在它的下面,所以人们知道x轴正在计数天。

On my x-axis, I have ticks from 1 to 10. I want the word "days" to appear underneath it so people know the x axis is counting days.

类似地,在y轴上,我将数字1-10作为刻度,并且我想要sandwiches eaten出现在侧面。

Similarly, on the y-axis, I have the numbers 1-10 as ticks, and I want the words "sandwiches eaten" to appear sideways.

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

Is there a simple way to do this?

推荐答案

Axis标签不内置于D3 ,但您可以自行添加标签,只需添加SVG text 元素。这方面的一个很好的例子是我重新创建Gapminder的动画气泡图表,。 x轴标签如下所示:

Axis labels aren't built-in to D3's axis component, but you can add labels yourself simply by adding an SVG text element. A good example of this is my recreation of Gapminder’s animated bubble chart, The Wealth & Health of Nations. The x-axis label looks like this:

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

您也可以使用样式表根据需要为这些标签设置样式, c> .label )或单独( .x.label .y.label )。

You can also use a stylesheet to style these labels as you like, either together (.label) or individually (.x.label, .y.label).

这篇关于d3轴标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 16:48