Published
Edited
Nov 21, 2021
Insert cell
Insert cell
chart = {
const svg = d3.create('svg')
.attr("viewBox", [0, 0, width, height]);
svg.append('g')
.selectAll('g')
.data(data)
.enter().append('g')
.attr("transform", d => `translate(${scale.x1(d.year)}, 0)`)
.selectAll('rect')
.data(d => data.filter(da => da.year == d.year))
.enter().append('rect')
.attr("x", d => scale.x2(d.index))
.attr("y", d => scale.y(d.value))
.attr("width", scale.x2.bandwidth())
.attr("height", d => scale.y(0) - scale.y(d.value))
.attr("fill", d => scale.c(d.index));
svg.append("g").call(xAxis1);
svg.append("g").call(yAxis);
return svg.node()
}
Insert cell
md`---`
Insert cell
md` ### Scale & Axis`
Insert cell
xAxis1 = g => g
.attr("transform", `translate(0, ${height - margin.bottom})`)
.call(d3.axisBottom(scale.x1))
// .call(g => g.selectAll(".domain").remove())
Insert cell
xAxis2 = g => g
.attr("transform", `translate(0, ${height - margin.bottom})`)
.call(d3.axisBottom(scale.x2))
.call(g => g.selectAll(".domain").remove())
// .text(data.x1))
Insert cell
yAxis = g => g
.attr("transform", `translate(${margin.left}, 0)`)
.call(d3.axisLeft(scale.y));
Insert cell
scale = {
// 년도별 scale
const x1 = d3.scaleBand()
.domain(data.reduce((acc, cur) => {
acc.push(cur.year);
const s = new Set(acc);
return Array.from(s);
}, []))
.range([margin.left, width - margin.right])
.paddingInner(0.1)
// 영화이름별 scale
const x2 = d3.scaleBand()
.domain(data.reduce((acc, cur) => {
acc.push(cur.index);
const s = new Set(acc);
return Array.from(s);
}, []))
.range([0, x1.bandwidth()])
.paddingInner(0.1);

const c = d3.scaleOrdinal()
.domain(d3.map(data, d => d.index))
.range(d3.schemePastel1);

const y = d3.scaleLinear()
.domain([0, d3.max(data, d => d.value)]).nice()
.range([height - margin.bottom, margin.top]);

return { x1, x2, c, y }
}
Insert cell
Insert cell
Insert cell
data = (await FileAttachment("movie2.json").json())
.sort((a, b) => a.year - b.year)
.reduce((acc, cur) => {
if (!!acc.length && acc[acc.length - 1].year === cur.year) {
cur.index = acc[acc.length - 1].index + 1;
} else {
cur.index = 0;
}
acc.push(cur);
return acc;
}, []);
Insert cell
Insert cell
Insert cell
height = 250
Insert cell
width = 500
Insert cell
margin = ({ top: 30, right: 0, bottom: 20, left: 70});
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