d3 axis labeling

后端 未结 6 1205
天涯浪人
天涯浪人 2020-12-12 15:55

How do I add text labels to axes in d3?

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

On my x-axis, I have ticks from 1 to 10. I want the wo

6条回答
  •  佛祖请我去吃肉
    2020-12-12 16:48

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

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

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

    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

提交回复
热议问题