Published
Edited
Dec 3, 2018
1 fork
Insert cell
Insert cell
chart = {
const svg = d3.select(DOM.svg(width, height));

svg.append("g")
.selectAll("g")
.data(data)
.enter().append("g")
.attr("fill", (d, i) => color(data.keys[i]))
.selectAll("rect")
.data(d => d)
.enter().append("rect")
.attr("x", (d, i) => x(data.names[i]))
.attr("y", d => y(d[1]))
.attr("height", d => y(d[0]) - y(d[1]))
.attr("width", x.bandwidth());

svg.append("g")
.call(xAxis);

svg.append("g")
.call(yAxis);

svg.append("g")
.attr("transform", `translate(${width - margin.right},${margin.top})`)
.call(legend);

return svg.node();
}
Insert cell
Insert cell
stackedData = d3.stack().keys(["テキスト", "スタンプ", "その他"])(csv)
Insert cell
csv = d3.csvParse(rawString, d => {
Object.keys(d).forEach( key => {
if (key == '日付') {
d[key] = new Date(d[key])
} else {
d[key] = + d[key]
}
})
return d
})
Insert cell
rawString = `日付,テキスト,スタンプ,その他
2018-01-01, 11, 12, 13
2018-01-02, 21, 32, 23
2018-01-03, 31, 32, 33
2018-01-04, 41, 42, 43
2018-01-05, 51, 52, 53
2018-01-06, 61, 62, 63
2018-01-07, 71, 72, 73
`
Insert cell
x = d3.scaleBand()
.domain(data.names)
.range([margin.left, width - margin.right])
.padding(0.1)
Insert cell
y = d3.scaleLinear()
.domain([0, d3.max(data.totals)])
.rangeRound([height - margin.bottom, margin.top])
Insert cell
color = d3.scaleOrdinal()
.unknown("#ccc")
.domain(data.keys)
// .range(['red', 'blue', 'green'])
.range(d3.quantize(t => d3.interpolateSpectral(t * 0.8 + 0.1), data.length).reverse())
Insert cell
d3.quantize(t => d3.interpolateSpectral(t * 0.8 + 0.1), data.length).reverse()
Insert cell
xAxis = g => g
.attr("transform", `translate(0,${height - margin.bottom})`)
.call(d3.axisBottom(x).tickSizeOuter(0).tickFormat(d3.timeFormat("%m/%d")))
.call(g => g.selectAll(".domain").remove())
Insert cell
yAxis = g => g
.attr("transform", `translate(${margin.left},0)`)
.call(d3.axisLeft(y).ticks(null, "s"))
.call(g => g.selectAll(".domain").remove())
Insert cell
legend = svg => {
const g = svg
.attr("font-family", "sans-serif")
.attr("font-size", 10)
.attr("text-anchor", "end")
.selectAll("g")
.data(data.keys.slice().reverse())
.enter().append("g")
.attr("transform", (d, i) => `translate(0,${i * 20})`);

g.append("rect")
.attr("x", -19)
.attr("width", 19)
.attr("height", 19)
.attr("fill", color);

g.append("text")
.attr("x", -24)
.attr("y", 9.5)
.attr("dy", "0.35em")
.text(d => d);
}
Insert cell
height = 600
Insert cell
margin = ({top: 10, right: 10, bottom: 20, left: 40})
Insert cell
d3 = require("d3@5")
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more