【问题标题】:d3.js Specify text for x-axisd3.js 为 x 轴指定文本
【发布时间】:2013-04-23 20:56:16
【问题描述】:

我的 x 轴当前有编号的刻度。我希望用我的对象中的数据(特别是 keyword 值)替换刻度。我将如何做到这一点?

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

【问题讨论】:

    标签: javascript d3.js axis-labels


    【解决方案1】:

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

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

    您可能需要稍微调整宽度以适应标签(或rotate them)。

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

    【讨论】:

    • 非常好。我试过类似的东西。但它一起打破了轴。但它现在有效!谢谢你。然后我添加了一些样式来旋转文本以防止它重叠。
    【解决方案2】:

    这称为序数轴,查看the example from the creator

    【讨论】:

      猜你喜欢
      • 2021-02-05
      • 2017-12-24
      • 1970-01-01
      • 2012-06-30
      • 2016-05-31
      • 2021-12-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多