Published
Edited
Jun 2, 2021
1 star
Insert cell
Insert cell
chartContainer = html`
<div style="width:400px;height:200px">
</div>
`
Insert cell
chart = new Chart()
.container(chartContainer)
.svgWidth(1000)
.data({ message: "Hello, I am chart, seriously..." })
.render()
Insert cell
class Chart {
constructor() {
this.state = {
svgWidth: 400,
svgHeight: 400,
marginTop: 5,
marginBottom: 5,
marginRight: 5,
marginLeft: 5,
container: d3.select("body")
};
}

container(newContainer) {
this.state.container = d3.select(newContainer);
return this;
}

svgWidth(newSvgWidth) {
this.state.svgWidth = newSvgWidth;
return this;
}

data(newData) {
this.state.data = newData;
return this;
}

// ================== RENDERING ===================
render() {
this.calculateProperties();
this.drawSvg();
this.drawContent();
return this;
}

drawContent() {
const { chart, data } = this.state;
// REMOVE THIS SNIPPET AFTER YOU START THE DEVELOPMENT
chart
.selectAll(".example-text")
.data([data])
.join("text")
.attr("class", "example-text")
.text((d) => d.message)
.attr("x", 10)
.attr("y", 20);
}

drawSvg() {
const {
container,
svgWidth,
svgHeight,
defaultFont,
calc,
data
} = this.state;

// Draw SVG
const svg = container
.selectAll(".svg-chart-container")
.data(["svg"])
.join("svg")
.attr("class", "svg-chart-container")
.attr("width", svgWidth)
.attr("height", svgHeight)
.attr("font-family", defaultFont);

//Add container g element
const chart = svg
.selectAll(".chart")
.data(["chart"])
.join("g")
.attr("class", "chart")
.attr(
"transform",
"translate(" + calc.chartLeftMargin + "," + calc.chartTopMargin + ")"
);

this.state = { ...this.state, chart, svg };
}

calculateProperties() {
const state = this.state;

//Calculated properties
var calc = {
chartTopMargin: null,
chartLeftMargin: null,
chartWidth: null,
chartHeight: null
};
calc.chartLeftMargin = state.marginLeft;
calc.chartTopMargin = state.marginTop;
calc.chartWidth = state.svgWidth - state.marginRight - calc.chartLeftMargin;
calc.chartHeight =
state.svgHeight - state.marginBottom - calc.chartTopMargin;

this.state = { ...this.state, calc };
}
}
Insert cell
Insert cell
d3 = require("d3@v6")
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