如何在y轴上移动d3刻度

时间:2016-06-08 11:49:56

标签: javascript d3.js

我有一个条形图see plunker问题是我想将y轴刻度移动到rects的中间左侧,但它们出现在顶部和末尾。而且我似乎无法在不破坏图表的情况下移动它们。

我的代码

var info = [{
        name: "Walnuts",
        value: 546546
      }, {
        name: "Almonds",
        value: 456455
      }

    ];

    /* Set chart dimensions */
    var width = 960,
      height = 500,
      margin = {
        top: 10,
        right: 10,
        bottom: 20,
        left: 60
      };

    //subtract margins
    width = width - margin.left - margin.right;
    height = height - margin.top - margin.bottom;

    //sort data from highest to lowest
    info = info.sort(function(a, b) {
      return b.value - a.value;
    });

    //Sets the y scale from 0 to the maximum data element


    var max_n = 0;
    var category = []
    for (var d in info) {
      max_n = Math.max(info[d].value, max_n);
      category.push(info[d].name)
    }

    var dx = width / max_n;
    var dy = height / info.length;

    var y = d3.scale.ordinal()
      .domain(category)
      .range([0, height]);

    var yAxis = d3.svg.axis()
      .scale(y)
      .orient('left')

    var svg = d3.select("#chart")
      .append("svg")
      .attr("width", "100%")
      .attr("height", "100%")
      .attr('preserveAspectRatio', 'xMidYMin')
      .attr("viewBox", '0 0 ' + parseInt(width + margin.left + margin.right) + ' ' + parseInt(height + margin.top + margin.bottom))
      .append("g")
      .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    svg.selectAll(".bar")
      .data(info)
      .enter()
      .append("rect")
      .attr("class", function(d, i) {
        return "bar" + d.name;
      })
      .attr("x", function(d, i) {
        return 0;
      })
      .attr("y", function(d, i) {
        return dy * i;
      })
      .attr("width", function(d, i) {
        return dx * d.value
      })
      .attr("height", dy)
      .attr("fill", function(d, i) {
        if (d.name == 'Walnuts') {
          return 'red'
        } else {
          return 'green'
        }
      });

    var y_xis = svg.append('g')
      .attr('id', 'yaxis')
      .call(yAxis);

3 个答案:

答案 0 :(得分:2)

您正在使用y轴范围,如下所示:

var y = d3.scale.ordinal()
      .domain(category)
      .range([0, height]);

你应该使用'rangeRoundBands',因为y比例是序数

   var y =   d3.scale.ordinal()
                        .domain(category)
                .rangeRoundBands([0, height], .1);

工作代码here

答案 1 :(得分:0)

对于d3版本(例如v4 / v5)。

myPlots <- function(data, column, fill_color) { # column = character name of column p <- ggplot(data, aes_string(x=column)) + geom_histogram(fill='red', binwidth=1, alpha=0.5, color='black') + scale_x_continuous(breaks=seq(floor(min(data[column])), ceiling(max(data[column])),1)) + ggtitle(column) max_count <- max(ggplot_build(p)$data[[1]]$count) p <- p + scale_y_continuous(breaks=seq(0,max_count,1)) return(p) } library(cowplot) plotList <- lapply(names(df), myPlots, data=df) plot_grid(plotlist = plotList) 定义为图形/图的高度,并将height定义为y的最大值。

max

答案 2 :(得分:0)

最近我需要一些非常相似的东西,我通过选择选择中的所有文本元素并向上移动它们的 dy 来解决这个问题。我将举例说明 OP 的代码:

   var y_xis = svg.append('g')
                      .attr('id','yaxis')
                      .call(yAxis)
                      .call(selection => selection
                          .selectAll('text')
                          .attr('dy', '-110') // this moves the text labels upwards
                          .attr('x', '110')); // this does the same job but horizontally