Javascript d3 轴标记

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11189284/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:51:13  来源:igfitidea点击:

d3 axis labeling

javascriptd3.jsaxis-labels

提问by user1474218

How do I add text labels to axes in d3?

如何将文本标签添加到 d3 中的轴?

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

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

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.

在我的 x 轴上,我有 1 到 10 的刻度。我希望“天”这个词出现在它下面,这样人们就知道 x 轴正在计算天数。

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

类似地,在 y 轴上,我将数字 1-10 作为刻度,并且我希望“吃的三明治”这个词横向出现。

Is there a simple way to do this?

有没有一种简单的方法可以做到这一点?

回答by mbostock

Axis labels aren't built-in to D3's axis component, but you can add labels yourself simply by adding an SVG textelement. 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:

轴标签不是 D3 的轴组件内置的,但您可以通过添加 SVGtext元素自行添加标签。一个很好的例子是我对 Gapminder 的动画气泡图“国家财富与健康”的再创作。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)");

And the y-axis label like this:

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

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

您还可以使用样式表根据需要设置这些标签的样式,可以一起 ( .label) 或单独 ( .x.label, .y.label)。

回答by ambodi

In the new D3js version (version 3 onwards), when you create a chart axis via d3.svg.axis()function you have access to two methods called tickValuesand tickFormatwhich are built-in inside the function so that you can specifies which values you need the ticks for and in what format you want the text to appear:

在新的 D3js 版本(版本 3 及更高版本)中,当您通过d3.svg.axis()函数创建图表轴时,您可以访问两个调用的方法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");

回答by Michael Clark

If you want the y-axis label in the middle of the y-axis like I did:

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

  1. Rotate text 90 degrees with text-anchor middle
  2. Translate the text by its midpoint
    • x position: to prevent overlap of y-axis tick labels (-50)
    • y position: to match the midpoint of the y-axis (chartHeight / 2)
  1. 使用文本锚中间旋转文本 90 度
  2. 按中点翻译文本
    • x 位置:防止 y 轴刻度标签重叠 ( -50)
    • y 位置:匹配 y 轴的中点 ( chartHeight / 2)

Code sample:

代码示例:

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

This prevents rotating the whole coordinate system as mentioned by lubar above.

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

回答by ColinE

D3 provides a pretty low-level set of components that you can use to assemble charts. You are given the building blocks, an axis component, data join, selection and SVG. It's your job to put them together to form a chart!

D3 提供了一组非常低级的组件,您可以使用它们来组装图表。您将获得构建块、轴组件、数据连接、选择和 SVG。您的工作是将它们放在一起形成图表!

If you want a conventional chart, i.e. a pair of axes, axis labels, a chart title and a plot area, why not have a look at d3fc? it is an open source set of more high-level D3 components. It includes a cartesian chart component that might be what you need:

如果您想要一个常规图表,即一对轴、轴标签、图表标题和绘图区域,为什么不看看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);

You can see a more complete example here: https://d3fc.io/examples/simple/index.html

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

回答by u7182389

If you work in d3.v4, as suggested, you can use this instance offering everything you need.

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

You might just want to replace the X-axis data by your "days" but remember to parse string values correctly and not apply concatenate.

您可能只想用“天数”替换 X 轴数据,但请记住正确解析字符串值而不是应用连接。

parseTime might as well do the trick for days scaling with a date format ?

parseTime 也可以用日期格式缩放天数吗?

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

fiddle with global css / js

摆弄全局 css / js

回答by Ravi Tej

chart.xAxis.axisLabel('Label here');

or

或者

xAxis: {
   axisLabel: 'Label here'
},