Public
Edited
Mar 24, 2023
Insert cell
Insert cell
Insert cell
simplePlot = Plot.plot({
x: { domain: company_sizes, tickRotate: 25 },
y: { percent: true, label: "% likelihood to provide mental health benefits" },
marks: [
Plot.barY(
us_only.filter((d) =>
["CA", "TX", "FL", "NY", "IL", "PA"].includes(d.state)
),
Plot.groupX(
{
y: "mean"
},
{
x: "no_employees",
fill: "no_employees",
y: (d) => (d.benefits === "Yes" ? 1 : 0),
fx: "state"
}
)
)
],
width,
marginBottom: 60
})
Insert cell
data = FileAttachment("MH.csv").csv({typed: true})
Insert cell
us_only= data.filter(function(d){ return (d.Country == "United States")})
Insert cell
company_sizes = {"1-5", "6-25" ,"26-100", "100-500","500-1000", "More than 1000"}
Insert cell
grouped_by_state = d3.group(us_only, d=> d.state)
Insert cell
state_objs = grouped_by_state.keys()
Insert cell
class state_obj {
constructor() {
this._name = "";
this._range1to5 = 0;
this._range6to25 = 0;
this._range25to100 = 0;
this._range100to500 = 0;
this._range500to1000 = 0;
this._rangemorethan1000 = 0;
}
}
Insert cell
// for each state, we want to group by company size, then for each company size, we count
{
var state_totals = [];
for (let i = 0; i < grouped_by_state.length; i++) {
console.log("Got into the loop");
var curr_state = grouped_by_state[i];
console.log(curr_state);
var total_responses = curr_state.size();
var total_yes_responses = d3
.group(curr_state, (d) => d.benefits == "Yes")
.size();
var grouped_by_company_size = d3.group(curr_state, (d) => d.no_employees);
var c_state_obj = state_obj();
c_state_obj.name = curr_state[0].state;
for (let j = 0; j < grouped_by_company_size.length; j++) {
var curr_size = grouped_by_company_size[j];
console.log(curr_size);
var yes_responses = d3.group(curr_size, (d) => d.benefits == "Yes");
var curr_yes_count = yes_responses.size();
if (curr_yes_count != 0 && total_yes_responses != 0) {
if (curr_size[0].no_employees == "1-5") {
c_state_obj.range1to5 = (curr_yes_count / total_yes_responses) * 100;
} else if (curr_size[0].no_employees == "6-25") {
c_state_obj.range6to25 = (curr_yes_count / total_yes_responses) * 100;
} else if (curr_size[0].no_employees == "25-100") {
c_state_obj.range25to100 =
(curr_yes_count / total_yes_responses) * 100;
} else if (curr_size[0].no_employees == "100-500") {
c_state_obj.range100to500 =
(curr_yes_count / total_yes_responses) * 100;
} else if (curr_size[0].no_employees == "500-1000") {
c_state_obj.range500to1000 =
(curr_yes_count / total_yes_responses) * 100;
} else {
c_state_obj.rangemorethan1000 =
(curr_yes_count / total_yes_responses) * 100;
}
}
}
state_totals.push(c_state_obj);
}
return state_totals;
}
Insert cell
Insert cell
chart = GroupedBarChart(stateages, {
x: d => d.state,
y: d => d.population / 1e6,
z: d => d.age,
xDomain: d3.groupSort(stateages, D => d3.sum(D, d => -d.population), d => d.state).slice(0, 6), // top 6
yLabel: "↑ Population (millions)",
zDomain: ages,
colors: d3.schemeSpectral[ages.length],
width,
height: 500
})
Insert cell
states = FileAttachment("us-population-state-age.csv").csv({typed: true})
Insert cell
ages = states.columns.slice(1)
Insert cell
stateages = ages.flatMap(age => states.map(d => ({state: d.name, age, population: d[age]}))) // pivot longer
Insert cell
Insert cell
Insert cell
// Copyright 2021 Observable, Inc.
// Released under the ISC license.
// https://observablehq.com/@d3/grouped-bar-chart
function GroupedBarChart(data, {
x = (d, i) => i, // given d in data, returns the (ordinal) x-value
y = d => d, // given d in data, returns the (quantitative) y-value
z = () => 1, // given d in data, returns the (categorical) z-value
title, // given d in data, returns the title text
marginTop = 30, // top margin, in pixels
marginRight = 0, // right margin, in pixels
marginBottom = 30, // bottom margin, in pixels
marginLeft = 40, // left margin, in pixels
width = 640, // outer width, in pixels
height = 400, // outer height, in pixels
xDomain, // array of x-values
xRange = [marginLeft, width - marginRight], // [xmin, xmax]
xPadding = 0.1, // amount of x-range to reserve to separate groups
yType = d3.scaleLinear, // type of y-scale
yDomain, // [ymin, ymax]
yRange = [height - marginBottom, marginTop], // [ymin, ymax]
zDomain, // array of z-values
zPadding = 0.05, // amount of x-range to reserve to separate bars
yFormat, // a format specifier string for the y-axis
yLabel, // a label for the y-axis
colors = d3.schemeTableau10, // array of colors
} = {}) {
// Compute values.
const X = d3.map(data, x);
const Y = d3.map(data, y);
const Z = d3.map(data, z);

// Compute default domains, and unique the x- and z-domains.
if (xDomain === undefined) xDomain = X;
if (yDomain === undefined) yDomain = [0, d3.max(Y)];
if (zDomain === undefined) zDomain = Z;
xDomain = new d3.InternSet(xDomain);
zDomain = new d3.InternSet(zDomain);

// Omit any data not present in both the x- and z-domain.
const I = d3.range(X.length).filter(i => xDomain.has(X[i]) && zDomain.has(Z[i]));

// Construct scales, axes, and formats.
const xScale = d3.scaleBand(xDomain, xRange).paddingInner(xPadding);
const xzScale = d3.scaleBand(zDomain, [0, xScale.bandwidth()]).padding(zPadding);
const yScale = yType(yDomain, yRange);
const zScale = d3.scaleOrdinal(zDomain, colors);
const xAxis = d3.axisBottom(xScale).tickSizeOuter(0);
const yAxis = d3.axisLeft(yScale).ticks(height / 60, yFormat);

// Compute titles.
if (title === undefined) {
const formatValue = yScale.tickFormat(100, yFormat);
title = i => `${X[i]}\n${Z[i]}\n${formatValue(Y[i])}`;
} else {
const O = d3.map(data, d => d);
const T = title;
title = i => T(O[i], i, data);
}

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;");

svg.append("g")
.attr("transform", `translate(${marginLeft},0)`)
.call(yAxis)
.call(g => g.select(".domain").remove())
.call(g => g.selectAll(".tick line").clone()
.attr("x2", width - marginLeft - marginRight)
.attr("stroke-opacity", 0.1))
.call(g => g.append("text")
.attr("x", -marginLeft)
.attr("y", 10)
.attr("fill", "currentColor")
.attr("text-anchor", "start")
.text(yLabel));

const bar = svg.append("g")
.selectAll("rect")
.data(I)
.join("rect")
.attr("x", i => xScale(X[i]) + xzScale(Z[i]))
.attr("y", i => yScale(Y[i]))
.attr("width", xzScale.bandwidth())
.attr("height", i => yScale(0) - yScale(Y[i]))
.attr("fill", i => zScale(Z[i]));

if (title) bar.append("title")
.text(title);

svg.append("g")
.attr("transform", `translate(0,${height - marginBottom})`)
.call(xAxis);

return Object.assign(svg.node(), {scales: {color: zScale}});
}
Insert cell
import {Legend, Swatches} from "@d3/color-legend"
Insert cell
import {howto, altplot} from "@d3/example-components"
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