【问题标题】:d3.js appending two labels from a dataset on the Y axisd3.js 在 Y 轴上附加来自数据集的两个标签
【发布时间】:2017-09-08 00:19:45
【问题描述】:

我的水平条形图数据是一组对象,如下所示: {值:-10,数据集:“Corvette”,年份:“1975”}。 “数据集”标签位于 y 轴上。我想将“年份”标签附加到“数据集”标签上,因此 y 轴上的标签如下所示:

克尔维特 1975

到目前为止,我可以将一个或另一个添加到 Y 轴,但不能同时添加。这是我的代码:

var margin = {top: 30, right: 10, bottom: 50, left: 50},
width = 500,
height = 300;

var data = [{value: -10, dataset:"Corvette", year: "1975"},
{value: 40, dataset:"Lumina", year: "1975"},
{value: -10, dataset:"Gran Torino", year: "1971"},
{value: -50, dataset:"Pomtiac GTO", year: "1964"},
{value: 30, dataset:"Mustang", year: "19655"},
{value: -20, dataset:"Camaro", year: "1973"},
{value: -70, dataset:"Firebird", year: "1975"}];

// Add svg to
var svg = d3.select('body').append('svg').attr('width', width +       margin.left + margin.right).attr('height', height + margin.top +       margin.bottom).append('g').attr('transform', 'translate(' + margin.left + ',' +     margin.top + ')');



// set the ranges
var y = d3.scaleBand()
.range([height, 0])
.padding(0.1);

var x = d3.scaleLinear()
.range([0, width]);

// Scale the range of the data in the domains
x.domain(d3.extent(data, function (d) {
    return d.value;
}));
y.domain(data.map(function (d) {
    return d.dataset;
}));

// append the rectangles for the bar chart
svg.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", function (d) {
    return "bar bar--" + (d.value < 0 ? "negative" : "positive");
})
.attr("x", function (d) {
    return x(Math.min(0, d.value));
})
.attr("y", function (d) {
    return y(d.dataset);
})
.attr("width", function (d) {
    return Math.abs(x(d.value) - x(0));
})
.attr("height", y.bandwidth());

// add the x Axis
svg.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));

// add the y Axis
 let yAxisGroup = svg.append("g")
.attr("class", "y axis")
.attr("transform", "translate(" + x(0) + ",0)")
.call(d3.axisRight(y));
yAxisGroup.selectAll('.tick')
.data(data)
.select('text')
.attr('x', function(d,i){return d.value<0?9:-9})
.style('text-anchor', function(d,i){return d.value<0?'start':'end'})

这是小提琴: https://jsfiddle.net/Kavitha_2817/2e1xLxLc/

【问题讨论】:

    标签: d3.js


    【解决方案1】:

    您可以将 d.dataset 和 d.year 的串联字符串映射到 y 比例,然后在使用该 y 比例定位矩形时使用相同的串联字符串。

    y 轴将使用该连接的字符串。

    示例:

    https://jsfiddle.net/2e1xLxLc/4/

    相关代码:

    //create a reusable function to concatenate the values you want to use
    function yValue(d) { return d.dataset + " " + d.year }
    
    // Scale the range of the data in the domains
    x.domain(d3.extent(data, function (d) {
        return d.value;
    }));
    y.domain(data.map(function(d){ return yValue(d) }));
    
    // append the rectangles for the bar chart
    svg.selectAll(".bar")
        .data(data)
        .enter().append("rect")
        .attr("class", function (d) {
            return "bar bar--" + (d.value < 0 ? "negative" : "positive");
        })
        .attr("x", function (d) {
            return x(Math.min(0, d.value));
        })
        .attr("y", function (d) {
            return y(yValue(d));
        })
        .attr("width", function (d) {
            return Math.abs(x(d.value) - x(0));
        })
        .attr("height", y.bandwidth());
    

    【讨论】:

      【解决方案2】:

      如果您(出于任何原因)想要保留相同的域,请使用 tickFormat 获取年份:

      .call(d3.axisRight(y)
          .tickFormat(function(d) {
              //filter the data array according to 'd', which is 'dataset'
              var filtered = data.filter(function(e) {
                  return e.dataset === d;
              })[0];
      
              //get the year in the 'filtered' object using 'filtered.year'
              return d + " " + filtered.year
          })
      );
      

      这是您的更改代码:

      var margin = {
          top: 30,
          right: 10,
          bottom: 50,
          left: 50
        },
        width = 500,
        height = 300;
      
      var data = [{
        value: -10,
        dataset: "Corvette",
        year: "1975"
      }, {
        value: 40,
        dataset: "Lumina",
        year: "1975"
      }, {
        value: -10,
        dataset: "Gran Torino",
        year: "1971"
      }, {
        value: -50,
        dataset: "Pomtiac GTO",
        year: "1964"
      }, {
        value: 30,
        dataset: "Mustang",
        year: "19655"
      }, {
        value: -20,
        dataset: "Camaro",
        year: "1973"
      }, {
        value: -70,
        dataset: "Firebird",
        year: "1975"
      }];
      
      // Add svg to
      var svg = d3.select('body').append('svg').attr('width', width + margin.left + margin.right).attr('height', height + margin.top + margin.bottom).append('g').attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
      
      // set the ranges
      var y = d3.scaleBand()
        .range([height, 0])
        .padding(0.1);
      
      var x = d3.scaleLinear()
        .range([0, width]);
      
      // Scale the range of the data in the domains
      x.domain(d3.extent(data, function(d) {
        return d.value;
      }));
      y.domain(data.map(function(d) {
        return d.dataset;
      }));
      
      // append the rectangles for the bar chart
      svg.selectAll(".bar")
        .data(data)
        .enter().append("rect")
        .attr("class", function(d) {
          return "bar bar--" + (d.value < 0 ? "negative" : "positive");
        })
        .attr("x", function(d) {
          return x(Math.min(0, d.value));
        })
        .attr("y", function(d) {
          return y(d.dataset);
        })
        .attr("width", function(d) {
          return Math.abs(x(d.value) - x(0));
        })
        .attr("height", y.bandwidth());
      
      // add the x Axis
      svg.append("g")
        .attr("transform", "translate(0," + height + ")")
        .call(d3.axisBottom(x));
      
      // add the y Axis
      let yAxisGroup = svg.append("g")
        .attr("class", "y axis")
        .attr("transform", "translate(" + x(0) + ",0)")
        .call(d3.axisRight(y)
          .tickFormat(function(d) {
            var filtered = data.filter(function(e) {
              return e.dataset === d;
            })[0];
            return d + " " + filtered.year
          })
        );
      yAxisGroup.selectAll('.tick')
        .data(data)
        .select('text')
        .attr('x', function(d, i) {
          return d.value < 0 ? 9 : -9
        })
        .style('text-anchor', function(d, i) {
          return d.value < 0 ? 'start' : 'end'
        })
      <style> .bar--positive {
        fill: steelblue;
      }
      
      .bar--negative {
        fill: darkorange;
      }
      
      </style>
      &lt;script src="https://d3js.org/d3.v4.min.js"&gt;&lt;/script&gt;

      【讨论】:

      • 很好的建议。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-02
      • 1970-01-01
      • 2019-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多