Public
Edited
Dec 18, 2023
Fork of Index chart
Insert cell
Insert cell
Insert cell
viewof value = {
// Specify the chart’s dimensions.
const width = 928;
const height = 600;
const marginTop = 20;
const marginRight = 40;
const marginBottom = 30;
const marginLeft = 40;

// Create the horizontal time scale.
const x = d3.scaleUtc()
.domain(d3.extent(stocks, d => d.Date))
.range([marginLeft, width - marginRight])
.clamp(true)

// 计算相对股价
// 初始值以第一周的股价为基准
// 💡 由于纵坐标轴采用了对数比例尺,所以当股价相差较大时,也不会造成较大范围的波动
// 可以通过垂直移动来表示相对值的变化
// Normalize the series with respect to the value on the first date. Note that normalizing
// the whole series with respect to a different date amounts to a simple vertical translation,
// thanks to the logarithmic scale! See also https://observablehq.com/@d3/change-line-chart
const series = d3.groups(stocks, d => d.Symbol).map(([key, values]) => {
const v = values[0].Close;
return {key, values: values.map(({Date, Close}) => ({Date, value: Close / v}))};
});

// Create the vertical scale. For each series, compute the ratio *s* between its maximum and
// minimum values; the path is going to move between [1 / s, 1] when the reference date
// corresponds to its maximum and [1, s] when it corresponds to its minimum. To have enough
// room, the scale is based on the series that has the maximum ratio *k* (in this case, AMZN).
const k = d3.max(series, ({values}) => d3.max(values, d => d.value) / d3.min(values, d => d.value));
const y = d3.scaleLog()
.domain([1 / k, k])
.rangeRound([height - marginBottom, marginTop])

// Create a color scale to identify series.
const z = d3.scaleOrdinal(d3.schemeCategory10).domain(series.map(d => d.Symbol));

// For each given series, the update function needs to identify the date—closest to the current
// date—that actually contains a value. To do this efficiently, it uses a bisector:
const bisect = d3.bisector(d => d.Date).left;

// Create the SVG container.
const svg = d3.create("svg")
.attr("width", width)
.attr("height", height)
.attr("viewBox", [0, 0, width, height])
.attr("style", "max-width: 100%; height: auto; -webkit-tap-highlight-color: transparent;");

// Create the axes and central rule.
svg.append("g")
.attr("transform", `translate(0,${height - marginBottom})`)
.call(d3.axisBottom(x).ticks(width / 80).tickSizeOuter(0))
.call(g => g.select(".domain").remove());

svg.append("g")
.attr("transform", `translate(${marginLeft},0)`)
.call(d3.axisLeft(y)
.ticks(null, x => +x.toFixed(6) + "×"))
.call(g => g.selectAll(".tick line").clone()
.attr("stroke-opacity", d => d === 1 ? null : 0.2)
.attr("x2", width - marginLeft - marginRight))
.call(g => g.select(".domain").remove());

// 垂直线,以表示当前采用哪一周的股价作为基准
const rule = svg.append("g")
.append("line")
.attr("y1", height)
.attr("y2", 0)
.attr("stroke", "black");

// Create a line and a label for each series.
const serie = svg.append("g")
.style("font", "bold 10px sans-serif")
.selectAll("g")
.data(series)
.join("g");

const line = d3.line()
.x(d => x(d.Date))
.y(d => y(d.value));

serie.append("path")
.attr("fill", "none")
.attr("stroke-width", 1.5)
.attr("stroke-linejoin", "round")
.attr("stroke-linecap", "round")
.attr("stroke", d => z(d.key))
.attr("d", d => line(d.values));

serie.append("text")
.datum(d => ({key: d.key, value: d.values[d.values.length - 1].value}))
.attr("fill", d => z(d.key))
.attr("paint-order", "stroke")
.attr("stroke", "white")
.attr("stroke-width", 3)
.attr("x", x.range()[1] + 3)
.attr("y", d => y(d.value))
.attr("dy", "0.35em")
.text(d => d.key);

// Define the update function, that translates each of the series vertically depending on the
// ratio between its value at the current date and the value at date 0. Thanks to the log
// scale, this gives the same result as a normalization by the value at the current date.
function update(date) {
date = d3.utcDay.round(date);
rule.attr("transform", `translate(${x(date) + 0.5},0)`);
serie.attr("transform", ({values}) => {
const i = bisect(values, date, 0, values.length - 1);
// 根据当前的基准股价,与第一周股价的比例,通过比例尺 y 的映射,计算出 series 系列折线在纵向 transition 需要移动的距离
return `translate(0,${y(1) - y(values[i].value / values[0].value)})`;
});
svg.property("value", date).dispatch("input"); // for viewof compatibility
}

// 刚进入网页时的动画
// Create the introductory animation. It repeatedly calls the update function for dates ranging
// from the last to the first date of the x scale.
d3.transition()
.ease(d3.easeCubicOut)
.duration(1500)
.tween("date", () => {
const i = d3.interpolateDate(x.domain()[1], x.domain()[0]);
return t => update(i(t));
});

// When the user mouses over the chart, update it according to the date that is
// referenced by the horizontal position of the pointer.
svg.on("mousemove touchmove", function(event) {
update(x.invert(d3.pointer(event, this)[0]));
d3.event.preventDefault();
});

// Sets the date to the start of the x axis. This is redundant with the transition above;
// uncomment if you want to remove the transition.
// update(x.domain()[0]);
return svg.node();
}
Insert cell
Insert cell
stocks = (await Promise.all([
FileAttachment("AAPL.csv").csv({typed: true}).then((values) => ["AAPL", values]),
FileAttachment("AMZN.csv").csv({typed: true}).then((values) => ["AMZN", values]),
FileAttachment("GOOG.csv").csv({typed: true}).then((values) => ["GOOG", values]),
FileAttachment("IBM.csv").csv({typed: true}).then((values) => ["IBM", values]),
FileAttachment("MSFT.csv").csv({typed: true}).then((values) => ["MSFT", values]),
])).flatMap(([Symbol, values]) => values.map(d => ({Symbol, ...d})))
Insert cell
Insert cell
Plot.plot({
y: {
type: "log",
grid: true,
label: "Change in price (%)",
tickFormat: ((f) => (x) => f((x - 1) * 100))(d3.format("+d"))
},
marks: [
Plot.ruleY([1]),
Plot.lineY(stocks, Plot.normalizeY({x: "Date", y: "Close", stroke: "Symbol"}))
]
})
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more