Published
Edited
Nov 4, 2020
15 stars
Insert cell
Insert cell
Insert cell
// Set a fixed width for the chart
fixed_width = 500;
Insert cell
// Creating an x scale that *isn't* tied to screen width
x = d3.scaleLinear()
.domain([0, 1])
.range([margin.left, fixed_width - margin.right])
Insert cell
Insert cell
fixed_width_chart = {
// Set the width using the fixed width
const svg = d3.create("svg")
.attr("width", fixed_width)
.attr("height", height)

svg.append("g")
.call(xAxis);

svg.append("g")
.call(yAxis);

svg.selectAll("circle")
.data(data)
.join("circle")
.attr("cx", d => x(d.x))
.attr("cy", d => y(d.y))
.attr("r", 10)

return svg.node();
}
Insert cell
Insert cell
viewbox_chart = {
const svg = d3.create("svg")
.attr("viewBox", [0, 0, fixed_width, height])

svg.append("g")
.call(xAxis);

svg.append("g")
.call(yAxis);
svg.selectAll("circle")
.data(data)
.join("circle")
.attr("cx", d => x(d.x))
.attr("cy", d => y(d.y))
.attr("r", 10)

return svg.node();
}
Insert cell
Insert cell
// Creating an x scale that *is* tied to screen width
x_screen = d3.scaleLinear()
.domain([0, 1])
.range([margin.left, width - margin.right]) // note the use of `width` here!
Insert cell
using_varying_scale = {
const svg = d3.create("svg")
.attr("viewBox", [0, 0, width, height]) // works the same if you set width and height here
// .attr("width", width)
// .attr("height", height)

svg.append("g")
.call(xAxis_screen);

svg.append("g")
.call(yAxis);
svg.selectAll("circle")
.data(data)
.join("circle")
.attr("cx", d => x_screen(d.x))
.attr("cy", d => y(d.y))
.attr("r", 10)

return svg.node();
}
Insert cell
Insert cell
y = d3.scaleLinear()
.domain([0, 1])
.range([height - margin.bottom, margin.top])
Insert cell
xAxis = g => g
.attr("transform", `translate(0,${height - margin.bottom})`)
.call(d3.axisBottom(x))
Insert cell
xAxis_screen = g => g
.attr("transform", `translate(0,${height - margin.bottom})`)
.call(d3.axisBottom(x_screen))
Insert cell
yAxis = g => g
.attr("transform", `translate(${margin.left},0)`)
.call(d3.axisLeft(y))
Insert cell
margin = ({top: 20, right: 30, bottom: 30, left: 40})
Insert cell
height = 300
Insert cell
d3 = require("d3@6")
Insert cell
_ = require("lodash")
Insert cell
// Some random numbers to plot
data = _.range(100).map(d => ({x:Math.random(), y:Math.random()}))
Insert cell
import {code_styles} from "@uw-info474/utilities"
Insert cell
code_styles
Insert cell
html`<style>
blockquote {
background-color: #d3d3d363;
padding:10px;
border-radius: 5px;
}
</style>`
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