Skip to content

Instantly share code, notes, and snippets.

Last active Jul 15, 2016
What would you like to do?
D3 v4 - barchart
license: gpl-3.0

D3.js ver.4 を使って作成したバーチャート

name value
hoge 100
hellow 312
world 222
fuga 254
<!DOCTYPE html>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<title>D3 v4 barChart</title>
#graph {
width: 900px;
height: 500px;
.tick line {
stroke-dasharray: 2 2 ;
stroke: #ccc;
<div id="graph"></div>
<script src="//"></script>
"use strict"
var width,height
var chartWidth, chartHeight
var margin
var svg ="#graph").append("svg")
var axisLayer = svg.append("g").classed("axisLayer", true)
var chartLayer = svg.append("g").classed("chartLayer", true)
var xScale = d3.scaleBand()
var yScale = d3.scaleLinear()
d3.csv("data.csv", cast, main)
function cast(d) {
d.value = +d.value
return d
function main(data) {
function setSize(data) {
width = document.querySelector("#graph").clientWidth
height = document.querySelector("#graph").clientHeight
margin = {top:0, left:100, bottom:40, right:0 }
chartWidth = width - (margin.left+margin.right)
chartHeight = height - (
svg.attr("width", width).attr("height", height)
axisLayer.attr("width", width).attr("height", height)
.attr("width", chartWidth)
.attr("height", chartHeight)
.attr("transform", "translate("+[margin.left,]+")")
xScale.domain({ return })).range([0, chartWidth])
.paddingInner(0.1) //バー間のパディング
.paddingOuter(0.5) //x軸両端のパディング
yScale.domain([0, d3.max(data, function(d){ return d.value})]).range([chartHeight, 0])
function drawChart(data) {
var t = d3.transition()
.on("start", function(d){ console.log("transiton start") }) //トランジション開始時
.on("end", function(d){ console.log("transiton end") }) //トランジション終了時
var bar = chartLayer.selectAll(".bar").data(data)
bar.enter().append("rect").classed("bar", true)
.merge(bar) //選択済みセレクションをenterで追加されるセレクションにマージする
.attr("fill", "blue")
.attr("width", xScale.bandwidth())
.attr("height", 0)
.attr("transform", function(d){ return "translate("+[xScale(, chartHeight]+")"})
.attr("height", function(d){ return chartHeight - yScale(d.value) })
.attr("transform", function(d){ return "translate("+[xScale(, yScale(d.value)]+")"})
function drawAxis(){
var yAxis = d3.axisLeft(yScale)
.attr("transform", "translate("+[margin.left,]+")")
.attr("class", "axis y")
var xAxis = d3.axisBottom(xScale)
.attr("class", "axis x")
.attr("transform", "translate("+[margin.left, chartHeight]+")")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment