Public
Edited
Apr 19, 2023
Insert cell
Insert cell
alphabet = FileAttachment("alphabet.csv").csv({typed: true})
Insert cell
Insert cell
Insert cell
// Copyright 2021 Observable, Inc.
// Released under the ISC license.
// https://observablehq.com/@d3/horizontal-bar-chart
{

const data = alphabet;
const marginLeft = 40;
const marginRight = 20;
const marginTop = 20;
const marginBottom = 40;
const width = 900;
const height = 500;
// Construct scales and axes.
const xScale = d3.scaleLinear()
.domain([0, d3.max(data, d => d.frequency)])
.range([marginLeft, width - marginRight]);

const yScale = d3.scaleBand()
.domain(data.map(d => d.letter))
.range([marginTop, height - marginBottom]).padding(0.1)
const xAxis = d3.axisBottom(xScale).ticks(5).tickSize(0).tickPadding(20);
const yAxis = d3.axisLeft(yScale).tickSize(0).tickPadding(20);

const svg = d3.create("svg")
.attr("width", width)
.attr("height", height)
.attr("viewBox", [0, 0, width, height])
.attr("style", "max-width: 100%; height: auto; height: intrinsic;");

// how to deal with axis in the same append group
svg.append("g")
.attr("transform", `translate(0,${height-marginBottom})`)
.call(xAxis)
.call(g => g.select(".domain").remove())
.call(g => g.selectAll(".tick text")
.attr("fill", "gray")
.attr("font-size", 14)
.attr("font-weight", "bold"))

svg.append("g")
.attr("fill", "#002EEE")
.selectAll("rect")
.data(data)
.join("rect")
.attr("rx", 5)
.attr("x", xScale(0))
.attr("y", d => yScale(d.letter))
.attr("width", d => xScale(d.frequency) - xScale(0))
.attr("height", yScale.bandwidth());


svg.append("g")
.attr("transform", `translate(${marginLeft},0)`)
.call(yAxis)
.call(g => g.select(".domain").remove())
.call(g => g.selectAll(".tick text")
.attr("fill", "gray")
.attr("font-size", 14)
.attr("font-weight", "bold"));

return svg.node();
}
Insert cell
import {howto, altplot} from "@d3/example-components"
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