JSFiddle - React, Tailwind, and code Playground

by Shang-De You

HTML

<button type="button" onclick="getData()">
  繪製圖表
</button>

JavaScript

var dataSet = []

var width = 400 // svg寬度
var height = 400 // svg寬度
var padding = { 
  top: 20,
  right: 20,
  bottom: 20,
  left: 20
} // 內距
var graphicHeight = height - padding.top - padding.bottom // 圖表高度為svg高度扣掉內距
var rectStep = 35 // 各別長條圖的距離
var rectWidth = 30 // 長條圖的寬度
var maxValue = 200 // 數值最大值

var svg = d3.select("body")
    .append("svg")
    .attr("width", width)
    .attr("height", height)
    
function getData(){
    
  dataSet = []
  
  var rand = d3.random.normal(100,30)
	
  for(var i = 0; i<7; i++){
  	var value = Math.round(rand())
    dataSet.push(value)
  }

  draw()
}

function draw(){

	// -- 繪製長條圖 --
	var updateRect = svg.selectAll("rect").data(dataSet)
  var enterRect = updateRect.enter()
  var exitRect = updateRect.exit()

  fillRect(updateRect)
  fillRect(enterRect.append("rect"))
	exitRect.remove()
  
  // -- 繪製數字 --
  var updateText = svg.selectAll("text").data(dataSet)
  var enterText = updateText.enter()
  var exitText = updateText.exit()

  fillText(updateText)
  fillText(enterText.append("text"))
	exitText.remove()
  
}

function fillRect(target){
	var linear = d3.scale.linear()
  	.domain([0,maxValue])
    .range([0,graphicHeight])

	target.attr("fill", "steelblue")
    .attr("x", function(d,i){
        return padding.left + i * rectStep
    })
    .attr("y", function(d){
    	return height - padding.bottom - linear(d)
    })
    .attr("width", rectWidth)
    .attr("height", function(d){
    	return linear(d)
    })
}

function fillText(target){
	target.attr("fill","white")
    .attr("font-size","14px")
    .attr("text-anchor","middle")
    .attr("x", function(d,i){
        return padding.left + i * rectStep
    })
    .attr("y", function(d){
        //return height - padding.bottom - d
      return height - padding.bottom - graphicHeight * (d / maxValue)
    })
    .attr("dx", rectWidth/2)
    .attr("dy", "1em")
    .text(function(d){
        return d
    })
}