Public
Edited
Nov 18, 2023
1 fork
1 star
Insert cell
Insert cell
Insert cell
chart = {
// Define dimensions
const width = 1194;
const height = 600;
const marginTop = 40;
const marginBottom = 50;
const marginRight = 32;
const marginLeft = 16;

// Define accessors
const xAccessor = (d) => d.totalRead; // horizontal
const yAccessor = (d) => d.publication; // vertical

// Define observation
const xObservations = d3.map(data, xAccessor);

// Define domains
const xDomain = [0, d3.max(xObservations)];
const yDomain = d3.groupSort(data, ([d]) => d.totalRead, yAccessor);

// Define range
const xRange = [marginLeft, width - marginRight];
const yRange = [height - marginBottom, marginTop];

// Define scale types
const xScaleType = d3.scaleLinear;
const yScaleType = d3.scaleBand;

// Declare the x (horizontal) and y (vertical) position scale.
const xScale = xScaleType(xDomain, xRange);
const yScale = yScaleType(yDomain, yRange).padding(0.1);

// Define axes
const xAxis = d3.axisTop(xScale).tickSizeOuter(0);

// Start drawing...
const svgEl = d3
.create("svg")
.attr("width", width)
.attr("height", height)
.attr("fill", "#0b0f0b")
.attr("viewBox", [0, 0, width, height]);

// Add the x-axis and label.
svgEl
.append("g")
.attr("transform", `translate(0,${marginTop})`)
.call(xAxis)
.call((g) => g.select(".domain").remove())
.call((g) =>
g
.selectAll(".tick:not(:first-child) line")
.clone()
.attr("y1", height - marginBottom - marginTop)
.attr("stroke-opacity", 0.3)
)
.call((g) =>
g
.append("text")
.attr("x", width - marginRight)
.attr("y", -marginTop + 15)
.attr("fill", "currentColor")
.attr("text-anchor", "end")
.text("Total articles read →")
);

// Add a rect for each bar.
svgEl
.append("g")
.classed("bars", true)
.attr("stroke", "#ff6d00")
.selectAll()
.data(data)
.join("rect")
.attr("y", (d) => yScale(d.publication))
.attr("x", marginLeft)
.attr("width", (d) => xScale(d.totalRead) - marginLeft)
.attr("height", yScale.bandwidth());

// Add the labels
svgEl
.append("g")
.classed("labels", true)
.attr("fill", "#d7d7db")
.selectAll()
.data(data)
.join("text")
.attr("x", marginLeft + 10)
.attr("y", (d) => yScale(d.publication) + 45)
.text((a) => `${a.publication} (${a.totalRead})`)
.attr("text-anchor", "start");

// Return the SVG element.
return svgEl.node();
}
Insert cell
data = FileAttachment("publications.json").json()
Insert cell
html`
<style type="text/css">
@import url('https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@600&display=swap');

svg {
max-width: 100%;
height: auto;
background-color: #0b0f0b;
color: #d7d7db;
font-family: "Space Grotesk";
font-weight: 600;
}
</style>
`
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