2015-10-15 94 views
1

我用D3.js繪製了一個折線圖。這是很好的淹沒,但有一點問題。問題是,y軸上的值沒有顯示在相應的點上。線的形狀也是正確的。但它從相應的位置向上移動。這是我的代碼,我在哪裏做錯了什麼?爲什麼y軸值從折線圖上的實際點上移?

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

 
var dataset = [ 
 
    {x: 0, y: true}, 
 
    {x: 1, y: true}, 
 
    {x: 2, y: false}, 
 
    {x: 3, y: true}, 
 
    {x: 4, y: true}, 
 
    {x: 5, y: true}, 
 
    {x: 6, y: true}, 
 
    
 
]; 
 

 
var xScale = d3.scale.linear() 
 
    .domain([0, d3.max(dataset, function(d){ return d.x; })]) 
 
    .range([0, width]); 
 

 
var yScale = d3.scale.ordinal() 
 
    .rangeRoundBands([0,height]); 
 
    
 
/*var yScale = d3.scale.linear() 
 
    .domain([0, 1]) 
 
    .range([height, 0]); 
 
*/ 
 
var xAxis = d3.svg.axis() 
 
    .scale(xScale) 
 
    .orient("bottom") 
 
    .innerTickSize(-height) 
 
    .outerTickSize(0) 
 
    .tickPadding(10); 
 
    
 

 

 
var yAxis = d3.svg.axis() 
 
    .scale(yScale) 
 
    .orient("left") 
 
    .innerTickSize(-width) 
 
    .outerTickSize(0) 
 
    .tickPadding(10); 
 
    
 
yScale.domain(dataset.map(function(d) {return d.y;}));   
 

 
var line = d3.svg.line() 
 
    .x(function(d) { return xScale(d.x); }) 
 
    .y(function(d) { return yScale(d.y); }); 
 

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

 
    svg.append("g") 
 
     .attr("class", "x axis") 
 
     .attr("transform", "translate(0," + height + ")") 
 
     .call(xAxis) 
 

 
    svg.append("g") 
 
     .attr("class", "y axis") 
 
     .call(yAxis) 
 

 
    svg.append("path") 
 
     .data([dataset]) 
 
     .attr("class", "line") 
 
     .attr("d", line);
.axis path, 
 
    .axis line{ 
 
    fill: none; 
 
    stroke: black; 
 
    } 
 

 
    .line{ 
 
    fill: none; 
 
    stroke: blue; 
 
    stroke-width: 2px; 
 
    } 
 

 
    .tick text{ 
 
    font-size: 12px; 
 
    } 
 

 
    .tick line{ 
 
    opacity: 0.2; 
 
    }
<!doctype html> 
 
<html lang="ja"> 
 
<head> 
 
    <meta charset="UTF-8"> 
 
    <title>Line Chart</title> 
 
</head> 
 
<body> 
 
<script src="http://d3js.org/d3.v3.js"></script> 
 

 
</body> 
 
</html>

感謝您的任何意見來解決這個問題。

回答

1

一個變化:

var yScale = d3.scale.ordinal() 
    .rangeRoundBands([0,height]); 

這本來

var yScale = d3.scale.ordinal() 
    .range([0,height]); 

工作撥弄here

希望這有助於!

+1

謝謝... :)它爲我工作.. +1 –