Public
Edited
Jan 31
Fork of D3 SVG
Insert cell
Insert cell
{
let data = [10,50,42];
let margin = 10;
// draw this data in three bars
// The current draw frame is from (10,10) to (490,490)
// make 50 the longest bar from 10 to 490
// notice the y coordinate is inverted!
const svgContainer = document.createElement("div");
// Calculating bar dimensions and spacing
const availableWidth = 490 - margin; // 490 is 500 - margin (right side)
const numberOfBars = data.length;
const spacing = 10; // Spacing between bars
const barWidth = (availableWidth - (numberOfBars - 0.1) * spacing - margin) / numberOfBars;

svgContainer.innerHTML = `
<svg width="500" height="500">
<line x1="${margin}" y1="${margin}" x2="${margin}" y2="${500 - margin}" stroke="blue" />
<line x1="${margin}" y1="${500 - margin}" x2="${500 - margin}" y2="${500 - margin}" stroke="blue" />
${data.map((value, index) => {
const height = (value / 50) * (500 - 2 * margin); // Scale height relative to max value 50
const x = margin + index * (barWidth + spacing);
const y = 500 - margin - height;
return `<rect x="${x}" y="${y}" width="${barWidth}" height="${height}" fill="black" />`;
}).join('')}
</svg>
`;
return svgContainer;
}
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