Published
Edited
Mar 28, 2022
Fork of Polar plot
Importers
5 stars
Insert cell
Insert cell
plot([(t) => Math.sin(4 * t), (t) => Math.sin(2 * t)])
Insert cell
function plot(fns = [(t) => t], options = {}) {
if (!Array.isArray(fns)) {
fns = [fns];
}
const {
width = 500,
height = 500,
domain = [0, 1],
resolution = 0.01
} = options;
const { radius = Math.min(width, height) / 2 - 30 } = options;

const svg = d3.create("svg").attr("width", width).attr("height", height);

const content = svg
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

const scale = d3.scaleLinear().domain(domain).range([0, radius]);
const grid = (g) => {
const gr = g
.attr("class", "r axis")
.selectAll("g")
.data(scale.ticks(5).slice(1))
.enter()
.append("g");

gr.append("circle").attr("r", scale);

gr.append("text")
.attr("y", function (d) {
return -scale(d) - 4;
})
.attr("transform", "rotate(15)")
.style("text-anchor", "middle")
.text(function (d) {
return d;
});
};
const axis = (g) => {
const ga = g
.attr("class", "a axis")
.selectAll("g")
.data(d3.range(0, 360, 30))
.enter()
.append("g")
.attr("transform", function (d) {
return "rotate(" + -d + ")";
});

ga.append("line").attr("x2", radius);

ga.append("text")
.attr("x", radius + 6)
.attr("dy", ".35em")
.style("text-anchor", function (d) {
return d < 270 && d > 90 ? "end" : null;
})
.attr("transform", function (d) {
return d < 270 && d > 90 ? "rotate(180 " + (radius + 6) + ",0)" : null;
})
.text(function (d) {
return d + "°";
});
};
const line = d3
.lineRadial()
.radius((d) => scale(d[1]))
.angle((d) => -d[0] + Math.PI / 2);
const curve = (g) => {
fns.forEach((fn) => {
const signal = d3
.range(0, 2 * Math.PI, resolution)
.map((t) => [t, fn(t)]);
g.append("path").datum(signal).attr("class", "line").attr("d", line);
});
};
content.append("g").call(grid);
content.append("g").call(axis);
content.append("g").attr("class", "data").call(curve);

const svgNode = svg.node();
const doc = html`
<style>

.axis text {
font: 10px sans-serif;
}

.axis line,
.axis circle {
fill: none;
stroke: #777;
stroke-dasharray: 1,4;
}

.axis :last-of-type circle {
stroke: #ddd;
stroke-dasharray: none;
}

.line {
fill: none;
stroke: #3B5FD7;
stroke-width: 1.5px;
}
.data > .line:nth-child(2) {
stroke: #e14747;
}
.data > .line:nth-child(3) {
stroke: #eac13b;
}
.data > .line:nth-child(3) {
stroke: #2f9666;
}

</style>
<div id="container">
<div class="chart">${svgNode}</div>
</div>
`;

return doc;
}
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