[英]d3 axis rendering outside the SVG
我正在向SVG添加兩個軸,但是,y軸在SVG的左側渲染:
如果我將方向設置為“右”,則將其渲染,但在左側:
代碼是這樣的:
'use strict';
var margins = {top: 50, bottom: 50, left: 50, right: 50};
var dateFormat = d3.time.format('%d-%b-%y')
var svg = d3.select('.graph');
var svgWidth = parseInt(svg.style('width')),
svgHeight = parseInt(svg.style('height'));
var height = svgHeight - margins.top - margins.bottom,
width = svgWidth - margins.left - margins.right;
var dates = [], closes = [];
data.forEach(function(item) {
dates.push(dateFormat.parse(item.date));
closes.push(item.close);
});
var xScale = d3.time.scale().range([0, width]).domain([d3.min(dates), d3.max(dates)]);
var yScale = d3.scale.linear().range([height, 0]).domain([0, d3.max(closes)]);
var xAxis = d3.svg.axis().scale(xScale).orient('bottom');
var yAxis = d3.svg.axis().scale(yScale).orient('right');
svg.append("g")
.attr("class", "x axis")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
任何g
的默認位置是(0, 0)
和.orient('left')
意味着軸位於場景之外的(0, 0)
的左側 。 您需要在包含軸的g
元素上手動設置transform
:
yAxis.orient('left');
svg.append('g')
.attr('class', 'y axis')
.attr('transform', 'translate(' + [margins.left, margins.top] + ')');
.call(yAxis);
使用推薦的表單,您缺少“繪圖區域” g
元素。
// have an SVG that is the drawing area width/height plus margins
// you don't show your mark-up but it looks like your code is ok
// append a `g` element and translate it to your margins
// you'll do all your drawing to the g element
svg = svg.append("g")
.attr("transform", "translate(" + margins.left + "," + margins.top + ")");
// append axis to this g
// your y-axis will be in the margin, so adjust margins.left to fit
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.