Public
Edited
Oct 25, 2023
1 star
Insert cell
Insert cell
plot = {
let w = 800;
let h = (2.1 * w) / 7;
let x_ticks = d3.range(-2 * Math.PI, 7, Math.PI / 2).filter((x) => x != 0);
let x_scale = d3.scaleLinear().domain([-7, 7]).range([0, w]);
let x_tick_labels = x_ticks.map(function (x) {
let n = Math.round((2 * x) / Math.PI);
let out = svg`<g transform="translate(${
x_scale(x) - (n == 1 ? 5 : n < -1 ? 14 : 10)
}, ${0.54 * h}) scale(1.2)">
${MathJax.tex2svg(
String.raw`${n == 1 ? "" : n == -1 ? "-" : n}\pi`
).querySelector("svg")}
</g>`;
return () => out;
});

let marks = [
Plot.axisX({
y: 0,
ticks: x_ticks,
tickFormat: () => ""
}),
Plot.axisY({
x: 0,
ticks: [-2, -1, 1, 2],
tickFormat: d3.format("d")
}),
Plot.ruleX([0]),
Plot.ruleY([0]),
Plot.line(
d3.range(-7, 7, 0.01).map((x) => [x, Math.sin(x)]),
{ strokeWidth: 3 }
)
].concat(x_tick_labels);

let plot = Plot.plot({
width: w,
height: h,
margin: 0,
x: { domain: [-7, 7] },
y: { domain: [-2.1, 2.1] },
marks: marks
});

return plot;
}
Insert cell
plot1 = {
let w = 800;
let h = (2.1 * w) / 7;
let x_ticks = d3.range(-2 * Math.PI, 7, Math.PI / 2).filter((x) => x != 0);
let x_scale = d3.scaleLinear().domain([-7, 7]).range([0, w]);

let plot = Plot.plot({
width: w,
height: h,
margin: 0,
x: { domain: [-7, 7] },
y: { domain: [-2.1, 2.1] },
marks: [
Plot.axisX({
y: 0,
ticks: x_ticks,
tickFormat: (x) => {
const n = Math.round((2 * x) / Math.PI);
return String.raw`${n == 1 ? "" : n == -1 ? "-" : n}\pi`;
},
render(index, scales, values, dimensions, context, next) {
const g = d3.create("svg:g", context.document);
const { x: X, y: Y, text: T } = values;

// tick labels
if (T) {
g.selectAll()
.data(index)
.enter()
.append("g")
.attr(
"transform",
(i) => `translate(${X[i]},${10 + Y[i]}) scale(1.2)`
)
.append((i) => MathJax.tex2svg(T[i]).querySelector("svg"));
return g.node();
}
// ticks
else return next(index, scales, values, dimensions, context);
}
}),
Plot.axisY({
x: 0,
ticks: [-2, -1, 1, 2],
tickFormat: d3.format("d")
}),
Plot.ruleX([0]),
Plot.ruleY([0]),
Plot.line(
d3.range(-7, 7, 0.01).map((x) => [x, Math.sin(x)]),
{ strokeWidth: 3 }
)
]
});

return plot;
}
Insert cell
MathJax = require("https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-svg.js").catch(
() => window["MathJax"]
)
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