简体   繁体   中英

D3 Line Chart into bindPopup

I'm a complete beginner to D3.js and I am trying to get a simple line chart into a leafletJS popup.

I am attempting to plot the values in the array against their index as practise.

This is the code that I have for the on click function:

point.on("click", function() {

  var div = $('<div style="width: 800px; height: 300px;"><svg/></div>')[0];
  this.bindPopup(div);
  this.openPopup();

  //data:
  var data = [3, 6, 2, 7, 5, 2, 0, 3, 8, 9, 2, 5, 9, 3, 6, 3, 6, 2, 7, 5, 2, 1, 3, 8, 9, 2, 5, 9, 2, 7];

  // set scales:
  var x = d3.scale.linear().domain([0,data.length]).range([0, 300]);
  var y = d3.scale.linear().domain([0,10]).range([0, 300]);

  // create axes:
  var xAxis = d3.svg.axis().scale(x).orient("bottom");
  var yAxis = d3.svg.axis().scale(y).orient("left");

  //construct line:
  var line = d3.svg.line()
    .x(function(d, i) {
      return x(i);
    })
    .y(function(d) {
      return y(d);
    });

  var svg = d3.select(div).append("svg")
    .attr("width", 600)
    .attr("height", 300)
    .append("g")
    .attr("transform", "translate(0,0)");

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

  svg.append("g")
    .attr("class", "y axis")
    .attr("transform", "translate(20,-150)")
    .call(yAxis);

  svg.append("path").attr("d", line(data));

})

This is the result that I get in my popup:

在此处输入图片说明

I am totally clueless on everything from the scale, to there being no line, to the y axis being below the x axis.

Any direction here would be much appreciated.

Thank you.

You have trasnalate instead of translate in your xAxis, that would explain the shift of the x bar.

Edit: my previous answer about reversing the y scale was incorrect. The following is more likely to be the cause of the problem:

About the scale, you forgot to mention the domain:

 var x = d3.scale.linear().domain([0, data.length]).range([0, 300]);
 var y = d3.scale.linear().domain([0, 10]).range([300, 0]);

Quoting the documentation:

d3.scale.linear() : Constructs a new linear scale with the default domain [0,1] and the default range [0,1].

For x you can safely keep data.length as a maximum value, for y you'll likely need to change the value 10 to fit your needs (you can also look for a maximum over the data array). But in any case [0,1] is too short.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM