javascript d3.js 指定 x 轴的文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16179021/
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-10-27 03:35:59  来源:igfitidea点击:

d3.js Specify text for x-axis

javascriptd3.jsaxis-labels

提问by EnigmaRM

My x-axis currently has numbered ticks. I want the ticks to be replaced with data from my object (specifically the keywordvalue). How would I accomplish this?

我的 x 轴目前有编号的刻度。我希望用来自我的对象的数据(特别是关键字值)替换刻度。我将如何做到这一点?

I have a working Fiddle

我有一个工作小提琴

var dataset = [
            {"keyword": "payday loans", "global": 1400000, "local": 673000, "cpc": "14.11"},
            {"keyword": "title loans", "global": 165000, "local": 160000, "cpc": "12.53" },
            {"keyword": "personal loans", "global": 550000, "local": 301000, "cpc": "6.14"},
            {"keyword": "online personal loans", "global": 15400, "local": 12900, "cpc": "5.84"},
            {"keyword": "online title loans", "global": 111600, "local": 11500, "cpc": "11.74"}
        ];

var xAxis = d3.svg.axis()
    .scale(xScale)
    .orient("bottom");
// xAxis
svg.append("g") // Add the X Axis
    .attr("class", "x axis")
    .attr("transform", "translate(0," + (h) + ")")
    .call(xAxis);
//xAxis Label
svg.append("text") 
    .attr("transform", "translate(" + (w / 2) + " ," + (h + margin.bottom - 5) +")")
    .style("text-anchor", "middle")
    .text("Keyword");

回答by Lars Kotthoff

The easiest way to achieve this is to set the tickFormatfunction for your axis:

实现此目的的最简单方法是tickFormat为您的轴设置函数:

var xAxis = d3.svg.axis()
    .scale(xScale)
    .tickFormat(function(d) { return dataset[d].keyword; })
    .orient("bottom");

You might have to tweak the width a bit to fit the labels (or rotate them).

您可能需要稍微调整宽度以适合标签(或旋转它们)。

The "proper" way to do this would be to specify the domain values for you xScaleas the keywords instead of the array indices. Then you would have to change all the other code that uses xScaleas well though.

执行此操作的“正确”方法是将域值指定xScale为关键字而不是数组索引。然后你将不得不更改所有其他使用的代码xScale

回答by mdubez

This is called an ordinal axis, check out the example from the creator

这称为序数轴,请查看创建者的示例