d3.js - 堆积图表中y轴的移动

12
我也在Google Group上发布了这个问题https://groups.google.com/forum/?fromgroups#!topic/d3-js/DYiVeC544ws,但看到它更喜欢在这里提问求助。我只是遇到了一个问题,就是如何将y轴移到图表的左侧,以免挡住第一列。我在Google Group上提供了一张图片,希望您能理解我的意思。
创建轴的代码如下:
   var MARGINS = {top: 20, right: 20, bottom: 20, left: 60}; // margins around the graph
var xRange = d3.scale.linear().range([MARGINS.left, width - MARGINS.right]), // x range function
    yRange = d3.scale.linear().range([height - MARGINS.top, MARGINS.bottom]), // y range function

    xAxis = d3.svg.axis().scale(xRange).tickSize(16).tickSubdivide(true), // x axis function
    yAxis = d3.svg.axis().scale(yRange).tickSize(10).orient("right").tickSubdivide(true); // y axis function


// create the visualization chart
var vis = d3.select("#chart")
   .append("svg")
    .attr("width", width)
    .attr("height", height + margin);


    // add in the x axis
  vis.append("svg:g") // container element
    .attr("class", "x axis") // so we can style it with CSS
    .attr("transform", "translate(0," + height + ")") // move into position
   // .call(xAxis); // add to the visualisation

  // add in the y axis
  vis.append("svg:g") // container element
    .attr("class", "y axis") // so we can style it with CSS
    .call(yAxis); // add to the visualisation
1个回答

25

使用transform属性来移动y轴,就像你为x轴所做的一样。例如:

svg.append("g")
    .attr("class", "y axis")
    .attr("transform", "translate(" + width + ",0)")
    .call(yAxis);

只有在使用正确的方向时才需要这样做。当轴向左时,通常默认定位就足够了。

此外,我建议使用以下约定来设置边距:

  • 将SVG元素的原点设置为内部图表区域的左上角。
  • widthheight定义为内部宽度和高度。

例如:

var margin = {top: 20, right: 10, bottom: 20, left: 10},
    width = 960 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

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

var y = d3.scale.linear()
    .range([height, 0]);

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

如果你愿意,你也可以存储内部和外部的尺寸,例如:

var outerWidth = 960,
    outerHeight = 500,
    innerWidth = outerWidth - margin.left - margin.right,
    innerHeight = outerHeight - margin.top - margin.bottom;

以下是该惯例的可视化解释:


感谢您的回复,我现在正在使用.attr("transform", "translate(" + width + ",0)"),但是我现在遇到了一个问题,我的堆叠条形图在最左边的列被截断了。原因是我必须将图形向右移动35像素,以便它不与x轴重叠。当我尝试增加画布大小时,图形只会按比例放大。是否可能在不缩放图形的情况下增加画布大小? - Apollo
听起来你的代码里可能有个 bug,也许是忘记减去一个边距。你试过我描述的规则了吗? - mbostock
经过一番折腾,我想我搞定了。是的,我目前正在使用你上面概述的约定。感谢您的帮助,我赞扬您的d3.js。这是一个很棒的库。 - Apollo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接