2015-11-01 2 views
2

Прошу прощения, поскольку я новичок в использовании графиков D3. Кажется, у меня проблема с графиком, появляющимся в очень странном/боковом направлении даже после сортировки. Я пытаюсь отобразить график, показывающий возрастающую тенденцию между двумя значениями. Значения из массива выглядят примерно так: [[200, 4.232660756790275], [300, 5.206851570440669], [400, 4.459431618637297]], где первое значение представлено на оси Y, а второе - по оси X. Ниже приведен код. Я делаю что-то неправильно? Пожалуйста, посоветуйте, спасибо.Javascript D3 graph, сортирующий график и оси

<!DOCTYPE html> 
<meta charset="utf-8"> 
<style> 

body { 
    font: 12px Arial; 
} 

text.shadow { 
    stroke: #fff; 
    stroke-width: 2.5px; 
    opacity: 0.9; 
} 

path { 
    stroke: steelblue; 
    stroke-width: 2; 
    fill: none; 
} 

.axis path, 
.axis line { 
    fill: none; 
    stroke: grey; 
    stroke-width: 1; 
    shape-rendering: crispEdges; 
} 

.grid .tick { 
    stroke: lightgrey; 
    stroke-opacity: 0.7; 
    shape-rendering: crispEdges; 
} 
.grid path { 
      stroke-width: 0; 
} 

.area { 
    fill: lightsteelblue; 
     stroke-width: 0; 
} 

</style> 
<body> 
<script src="http://d3js.org/d3.v3.min.js"></script> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

<script> 

var margin = {top: 30, right: 20, bottom: 35, left: 50}, 
    width = 600 - margin.left - margin.right, 
    height = 270 - margin.top - margin.bottom; 

//var parseDate = d3.time.format("%d-%b-%y").parse; 
var arrData = JSON.parse(window.localStorage.getItem("graphArray")); 

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

var xAxis = d3.svg.axis() 
    .scale(x) 
    .orient("bottom") 
    .ticks(5); 

var yAxis = d3.svg.axis() 
    .scale(y) 
    .orient("left") 
    .ticks(5); 

var area = d3.svg.area() 
    .x(function(d) { return x(d.idd); }) 
    .y0(height) 
    .y1(function(d) { return y(d.timing); }); 

var valueline = d3.svg.line() 
    .x(function(d) { return x(d.idd); }) 
    .y(function(d) { return y(d.timing); }); 

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 data = arrData.map(function(d) { 
    return { 

     idd: d[1], 
     timing: d[0] 

    }; 

}); 

console.log(data); 

// function for the x grid lines 
function make_x_axis() { 
    return d3.svg.axis() 
     .scale(x) 
     .orient("bottom") 
     .ticks(5) 
} 

// function for the y grid lines 
function make_y_axis() { 
    return d3.svg.axis() 
     .scale(y) 
     .orient("left") 
     .ticks(5) 
} 

    // Scale the range of the data 
    x.domain(d3.extent(data, function(d) { return d.idd; })); 
    y.domain([0, d3.max(data, function(d) { return d.timing; })]); 

    // Add the filled area 
    svg.append("path") 
     .datum(data) 
     .attr("class", "area") 
     .attr("d", area); 

    // Draw the x Grid lines 
    svg.append("g") 
     .attr("class", "grid") 
     .attr("transform", "translate(0," + height + ")") 
     .call(make_x_axis() 
      .tickSize(-height, 0, 0) 
      .tickFormat("") 
     ) 

    // Draw the y Grid lines 
    svg.append("g")    
     .attr("class", "grid") 
     .call(make_y_axis() 
      .tickSize(-width, 0, 0) 
      .tickFormat("") 
     ) 

    // Add the valueline path. 
    svg.append("path") 
     .attr("d", valueline(data)); 

    // Add the X Axis 
    svg.append("g") 
     .attr("class", "x axis") 
     .attr("transform", "translate(0," + height + ")") 
     .call(xAxis); 

    // Add the Y Axis 
    svg.append("g") 
     .attr("class", "y axis") 
     .call(yAxis); 

    // Add the text label for the X axis 
    svg.append("text") 
     .attr("transform", 
       "translate(" + (width/2) + " ," + 
          (height+margin.bottom) + ")") 
     .style("text-anchor", "middle") 
     .text("Index of Difficulty"); 

    // Add the white background to the y axis label for legibility 
    svg.append("text") 
     .attr("transform", "rotate(-90)") 
     .attr("y", 6) 
     .attr("x", margin.top - (height/2)) 
     .attr("dy", ".71em") 
     .style("text-anchor", "end") 
     .attr("class", "shadow") 
     .text("Price ($)"); 

    // Add the text label for the Y axis 
    svg.append("text") 
     .attr("transform", "rotate(-90)") 
     .attr("y", 6) 
     .attr("x", margin.top - (height/2)) 
     .attr("dy", ".71em") 
     .style("text-anchor", "end") 
     .text("Time (ms)"); 

    // Add the title 
    svg.append("text") 
     .attr("x", (width/2))  
     .attr("y", 0 - (margin.top/2)) 
     .attr("text-anchor", "middle") 
     .style("font-size", "16px") 
     .style("text-decoration", "underline") 
     .text("Fitts' Law"); 


</script> 
</body> 

А что граф выглядит как после прохождения в данных из массива: Кроме того, мне было интересно, как я могу изменить текст для X-оси, как представляется, не в пределах диапазона значений, который извлекается ,

enter image description here

ответ

2

не понимают, почему вы определили ось х как временная шкала.

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

Просто читая переменную кажется, что это какой-то идентификатор

Так должно быть

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

Далее график правильно данные в таком порядке

[[200, 4.232660756790275], [300, 5.206851570440669], [400, 4.459431618637297]]; 

, так что сначала он доходит до 4.3, затем до 5.2, а затем обратно в 4.4, вот почему его приближение подобно воображению e показано в вопросе.

Я бы порекомендовал вам сортировать данные, как ниже, так что порядок теперь 4,23 затем 4,45 затем 5,20 ...

data.sort(function(a, b) { 
    return a.idd - b.idd; 
}); 

Это позволит сделать график, как, как вы хотите :)

Рабочий код here

Надеюсь, это поможет!

+1

спасибо !! Теперь я понимаю! Огромное спасибо!! – user1610834

Смежные вопросы