iT邦幫忙

0

我目前D3的長條圖是v7的 但我和我其他的D3程式不兼容 請問我要如何把它改成v3的版本呢?

  • 分享至 

  • xImage
<script>
  
  // 資料變換
  
  let url = './CSV/110年數量.csv'//110
  var A=1;//預設長條圖年份值
  d3.select('.Eight')
    .on('click', function(){
      url = './CSV/108年數量.csv' //108.csv
      A=3;
      getData()
      
      
    })
    d3.select('.Nine')
    .on('click', function(){
      url = './CSV/109年數量.csv' //109.csv
      A=2;
      getData()
      
      
    })

  d3.select('.July')
    .on('click', function(){
      url = './CSV/110年數量.csv' //110.csv
      A=1;
      getData()
      
      
    })
  d3.select('.August')
    .on('click', function(){
      url = './CSV/111年數量.csv' //111.csv
      A=0;
      getData()
    
      
    })

  let data = []
  async function getData() {
    // 取資料
    dataGet = await d3.csv(url)
    console.log(dataGet)
    data = dataGet
    drawBarChart()
  };
  getData()


  // RWD
  function drawBarChart(){
    // 刪除原本的svg.charts,重新渲染改變寬度的svg
    d3.select('.chart svg').remove();

    // RWD 的svg 寬高
    const rwdSvgWidth = parseInt(d3.select('.chart').style('width')),
          rwdSvgHeight = rwdSvgWidth*0.8,
          margin = 40;

    const svg = d3.select('.chart')
                  .append('svg')
                  .attr('width', rwdSvgWidth)
                  .attr('height', rwdSvgHeight);
                  
                  
                  

    // map 資料集
    xData = data.map((i) => i['月份']);//月份  捕捉數量
    yData = data.map((i) => parseInt(i['捕捉數量'].split(',').join('')));
   
    // 設定要給 X 軸用的 scale 跟 axis
    const xScale = d3.scaleBand()
                    .domain(xData)
                    .range([margin*2, rwdSvgWidth - margin/2]) // 寬度
                    .padding(0.2)

    const xAxis = d3.axisBottom(xScale)

    // 呼叫繪製x軸、調整x軸位置
    const xAxisGroup = svg.append("g")
                          .call(xAxis)
                          .attr("transform", `translate(0,${rwdSvgHeight - margin})`)
                          .selectAll("text") // 調整刻度文字標籤傾斜
                          .attr("transform", "translate(-10,0)rotate(-45)")
                          .style("text-anchor", "end");

    // 設定要給 Y 軸用的 scale 跟 axis
    const yScale = d3.scaleLinear()
                    .domain([0, d3.max(yData)])
                    .range([rwdSvgHeight - margin, margin]) // 數值要顛倒,才會從低往高排
                    .nice() // 補上終點值

    const yAxis = d3.axisLeft(yScale)
                    .ticks(5)
                    .tickSize(3)

    // 呼叫繪製y軸、調整y軸位置
    const yAxisGroup = svg.append("g")
                          .call(yAxis)
                          .attr("transform", `translate(${margin*2},0)`)
                          
                    
    // 開始建立長條圖
    const bar = svg.selectAll("rect")//長條圖我們會使用< rect >來建立
                  .data(data)
                  .join("rect")

    // 加上漸增動畫,注意如果要加動畫,event 要分開寫
    bar.attr("x", d => xScale(d['月份'])) // 讓長條圖在刻度線中間
      .attr('y', yScale(0))
      .attr("width", xScale.bandwidth())
      .transition()
      .duration(1000)
      .delay((d, i)=> i*100)
      .attr("y", d => yScale(parseInt(d['捕捉數量'].split(',').join(''))))
      .attr("height", d => { //把高度設定成從「圖表高度 — 直條圖高度」的地方開始繪製,才能畫出正確高度的圖表
                return (rwdSvgHeight - margin) - yScale(parseInt(d['捕捉數量'].split(',').join('')))
              })
      .attr("fill", "#69b3a2")

    // 加上滑鼠事件       
    bar.attr('cursor', 'pointer')
        .on("mouseover", handleMouseOver)
        .on("mouseleave", handleMouseLeave)
        
        let a = ['111年','110年','109年','108年'];
    function year(r){
        svg.append("text")
        .attr("class", "title")
        .attr("x", 180)
        .attr("y", 40)
        .attr("width",10)
        .attr("height",10)
        .attr("text-anchor", "middle")
        .text(a[r]);
        
    }
        year(A)//畫出年份標題

       

        function handleMouseOver(d, i){
      // console.log(d)
      // console.log(d.target.__data__)
      d3.select(this)
        .attr('fill', 'red')
      
      // 加上文字標籤
      svg.append('text')//總數標籤
         .attr('class', 'infoText')
         .attr('y', yScale(parseInt(d.target.__data__['捕捉數量'].split(',').join(''))))
         .attr("x", xScale(d.target.__data__['月份']) )
        
         .style('z-index','20')
         .style('fill', '#000')
         .style('font-size', '16px')
         .style('font-weight', 'bold')
         .style("text-anchor", 'middle')
         
         .text('總數:'+d.target.__data__['捕捉數量'] );

         svg.append('text')//本島標籤
         .attr('class', 'infoText1')
         .attr('y', yScale(parseInt(d.target.__data__['捕捉數量'].split(',').join('')))-15)
         .attr("x", xScale(d.target.__data__['月份']) )
         
         .style('z-index','20')
         .style('fill', '#000')
         .style('font-size', '16px')
         .style('font-weight', 'bold')
         .style("text-anchor", 'middle')
         
         .text('本島:'+d.target.__data__['本島']);

         svg.append('text')//離島標籤
         .attr('class', 'infoText2')
         .attr('y', yScale(parseInt(d.target.__data__['捕捉數量'].split(',').join('')))-30)
         .attr("x", xScale(d.target.__data__['月份']) )
         
         .style('z-index','20')
         .style('fill', '#000')
         .style('font-size', '16px')
         .style('font-weight', 'bold')
         .style("text-anchor", 'middle')
         .text('離島:'+d.target.__data__['離島']);
         
            
         
         
         
    }

    function handleMouseLeave(){
      d3.select(this)
        .attr('fill', '#69b3a2')

      // 移除文字標籤
      svg.select('.infoText').remove()
      svg.select('.infoText1').remove()
      svg.select('.infoText2').remove()
    }
}

  d3.select(window).on('resize', drawBarChart);


</script>
Xiang1009 iT邦研究生 5 級 ‧ 2022-08-23 01:35:12 檢舉
看兩個版本的document差異在哪再做修正,我個人是不用高度客製化圖表所以用C3。我自身經驗是都用同版本的框架開發比較好,不同版本無法確定何時會出狀況。
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友回答

立即登入回答