簡體   English   中英

是否可以在d3中創建動態網格折線圖?

[英]is it possible to create a dynamic grid line chart in d3?

我正在d3中開發散點圖,您可以在其中使用下拉菜單更改x軸和y軸。

我能夠繪制網格線,但是當為x軸或y軸選擇新值時,我的問題是重新繪制它們。

我希望有人可以建議我該怎么做。

這是到目前為止我的代碼(js):

d3.csv('data.csv',function (data) {
// CSV section
  var body = d3.select('body')
  var selectData = [ { "text" : "Trust words" },
                     { "text" : "Surprise words" },
                     { "text" : "Sadness words" },
                     { "text" : "Positive words"},
                     { "text" : "Negative words"},
                     { "text" : "Fear words"},
                     { "text" : "Disgust words"},
                     { "text" : "Anticipation words"},
                     { "text" : "Anger words"},
                   ]

  // Select X-axis Variable
  var span = body.append('span')
    .text('Select an Emotion word for the Horizontal scale: ')
  var xInput = body.append('select')
      .attr('id','xSelect')
      .on('change',xChange)
    .selectAll('option')
      .data(selectData)
      .enter()
    .append('option')
      .attr('value', function (d) { return d.text })
      .text(function (d) { return d.text ;})
  body.append('br')
  body.append('br')

  // Select Y-axis Variable
  var span = body.append('span')
      .text('Select an Emotion word for the Vertical scale: ')
  var yInput = body.append('select')
      .attr('id','ySelect')
      .on('change',yChange)
    .selectAll('option')
      .data(selectData)
      .enter()
    .append('option')
      .attr('value', function (d) { return d.text })
      .text(function (d) { return d.text ;})
  body.append('br')

  // Variables
  var body = d3.select('body')
  var margin = { top: 50, right: 50, bottom: 50, left: 50 }
  var h = 700 - margin.top - margin.bottom
  var w = 1350 - margin.left - margin.right
  var rscale = d3.scale.linear()
  // Scales
  var cValue = function(d) { if (parseFloat(d['Emotions words']) >=0 && parseFloat(d['Emotions words']) <= 200000) return 'Emotion Words NO: 0-200,000 inc'
                               else if(parseFloat(d['Emotions words']) >200000 && parseFloat(d['Emotions words']) <=350000) return 'Emotion Words NO: 200,001-350,000 inc'
                               else return 'Emotion words NO: >350,000'},
        color = d3.scale.category10();  
  var xScale = d3.scale.linear()
    .domain([
      d3.min([0,d3.min(data,function (d) { return parseFloat(d['Trust words']) })]),
      d3.max([0,d3.max(data,function (d) { return parseFloat(d['Trust words']) })])
      ])
    .range([0,w])
  var yScale = d3.scale.linear()
    .domain([
      d3.min([0,d3.min(data,function (d) { return parseFloat(d['Trust words']) })]),
      d3.max([0,d3.max(data,function (d) { return parseFloat(d['Trust words']) })])
      ])
    .range([h,0])

  // SVG
  var svg = body.append('svg')
      .attr('height',h + margin.top + margin.bottom)
      .attr('width',w + margin.left + margin.right)
    .append('g')
      .attr('transform','translate(' + margin.left + ',' + margin.top + ')')
  // X-axis
  var xAxis = d3.svg.axis()
    .scale(xScale)
    .orient('bottom')
    .ticks(5)
  // Y-axis
  var yAxis = d3.svg.axis()
    .scale(yScale)
    .orient('left')
    .ticks(5)
function make_x_axis() {        
    return d3.svg.axis()
        .scale(xScale)
         .orient("bottom")
         .ticks(5)
}

function make_y_axis() {        
    return d3.svg.axis()
        .scale(yScale)
        .orient("left")
        .ticks(5)
}   
  // Circles
  var circles = svg.selectAll('circle')
      .data(data)
      .enter()
    .append('circle')
      .attr('cx',function (d) { return xScale(d['Trust words']) })
      .attr('cy',function (d) { return yScale(d['Trust words']) })
      .attr('r',function (d) { return rscale(d['Average_movie_rating'])*2;})
      .attr('stroke','black')
      .attr('stroke-width',1)
      .attr('fill',function (d) { return color(cValue(d)); })
      .on('mouseover', function () {
        d3.select(this)
          .transition()
          .duration(500)
          .attr('r',20)
          .attr('stroke-width',3)
      })
      .on('mouseout', function () {
        d3.select(this)
          .transition()
          .duration(500)
          .attr('r',10)
          .attr('stroke-width',1)
      })
    .append('title') // Tooltip
      .text(function (d) { return 'Actor Name: ' + d['Actor_ Name'] +
                           '\nTrust words: ' + d['Trust words'] +
                           '\nSurprise words: '  + d['Surprise words']+
                           '\nSadness words: ' + d['Sadness words'] +
                           '\nPositive words: ' + d['Positive words'] +
                           '\nNegative words: ' + d['Negative words'] +
                           '\nFear words: ' + d['Fear words'] +
                           '\nDisgust words: ' + d['Disgust words'] +
                           '\nAnticipation words: ' + d['Anticipation words'] +
                           '\nAnger words: ' + d['Anger words'] +
                           '\nAverage ranking: '+ d['Average_movie_rating']})

  // X-axis
  svg.append('g')
      .attr('class','axis')
      .attr('id','xAxis')
      .attr('transform', 'translate(0,' + h + ')')
      .call(xAxis)
    .append('text') // X-axis Label
      .attr('id','xAxisLabel')
      .attr('y',-10)
      .attr('x',w)
      .attr('dy','.71em')
      .style('text-anchor','end')
      .text('Trust words')
  // Y-axis
  svg.append('g')
      .attr('class','axis')
      .attr('id','yAxis')
      .call(yAxis)
    .append('text') // y-axis Label
      .attr('id', 'yAxisLabel')
      .attr('transform','rotate(-90)')
      .attr('x',0)
      .attr('y',5)
      .attr('dy','.71em')
      .style('text-anchor','end')
      .text('Trust words')
  svg.append('g')         
        .attr("class", "grid")
        .attr("transform", "translate(0," + h + ")")
        .call(make_x_axis()
            .tickSize(-h, 0, 0)
            .tickFormat("")
        )   
  svg.append('g')         
        .attr("class", "grid")
        .call(make_y_axis()
            .tickSize(-w, 0, 0)
            .tickFormat("")
        )


  function yChange() {
    var value = this.value // get the new y value
    yScale // change the yScale
      .domain([
        d3.min([0,d3.min(data,function (d) { return parseFloat(d[value]) })]),
        d3.max([0,d3.max(data,function (d) { return parseFloat(d[value]) })])
        ])
    yAxis.scale(yScale) // change the yScale
    d3.select('#yAxis') // redraw the yAxis
      .transition().duration(1000)
      .call(yAxis)
    d3.select('#yAxisLabel') // change the yAxisLabel
      .text(value)    
    d3.selectAll('circle') // move the circles
      .transition().duration(1000)
      .delay(function (d,i) { return i*100})
        .attr('cy',function (d) { return yScale(d[value]) })

  }

  function xChange() {
    var value = this.value // get the new x value
    xScale // change the xScale
      .domain([
        d3.min([0,d3.min(data,function (d) { return parseFloat(d[value]) })]),
        d3.max([0,d3.max(data,function (d) { return parseFloat(d[value]) })])
        ])
    xAxis.scale(xScale) // change the xScale
    d3.select('#xAxis') // redraw the xAxis
      .transition().duration(1000)
      .call(xAxis)
    d3.select('#xAxisLabel') // change the xAxisLabel
      .transition().duration(1000)
      .text(value)
    d3.selectAll('circle') // move the circles
      .transition().duration(1000)
      .delay(function (d,i) { return i*100})
        .attr('cx',function (d) { return xScale(d[value]) })
  }
    var legend = svg.selectAll(".legend")
          .data(color.domain())
        .enter().append("g")
          .attr("class", "legend")
          .attr("transform", function(d, i) { return "translate(0," + i * 25 + ")"; });

      // draw legend colored rectangles
      legend.append("rect")
          .attr("x", w + 25)
          .attr("y", 490)
          .attr("width", 18)
          .attr("height", 18)
          .style("fill", color);

      // draw legend text
      legend.append("text")
          .attr("x", w - 24)
          .attr("y", 500)
          .attr("dy", ".35em")
          .style("text-anchor", "end")
          .text(function(d) { return d;})
          .text(function(d) { return d;})
})

謝謝

抱歉,我想寫評論,但我的聲譽不高,所以我必須寫這個作為答案。 您是否有可能提供一個小型數據集,以便我可以在計算機上運行此代碼? 如果我有運行數據集的代碼,那么更容易理解代碼應該如何工作。

另外,網格線是什么意思? 如果您指的是刻度線,那么我認為無論您使用什么規模,刻度線都不會改變。 您將其設置為5,所以我認為總會有5個等距的刻度線。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM