// Generate sample data
data = {
const n = 200;
const control = Array.from({length: n}, () => ({
group: "Control",
rate: Math.min(100, Math.max(0, d3.randomNormal(30, 12)()))
}));
const intervention = Array.from({length: n}, () => ({
group: "Intervention",
rate: Math.min(100, Math.max(0, d3.randomNormal(10, 8)()))
}));
return [...control, ...intervention];
}9 Data relationships
more extensive data relationships and visualisations that require central tendency
flow charts what chart to choose for what visualisation?
// Summary statistics
summary = {
const groups = d3.group(data, d => d.group);
return Array.from(groups, ([group, values]) => {
const rates = values.map(d => d.rate);
const mean = d3.mean(rates);
const sd = d3.deviation(rates);
const median = d3.median(rates);
const q1 = d3.quantile(rates.sort(d3.ascending), 0.25);
const q3 = d3.quantile(rates.sort(d3.ascending), 0.75);
const min = d3.min(rates);
const max = d3.max(rates);
return {group, mean, sd, median, q1, q3, min, max};
});
}viewof chartType = Inputs.radio(
["Bar Chart", "Boxplot"],
{label: "Chart Type:", value: "Bar Chart"}
)
viewof showColor = Inputs.toggle({label: "Color by Group", value: true})
viewof showSD = Inputs.toggle({
label: "Show Standard Deviation",
value: false,
disabled: chartType === "Boxplot"
})
viewof showStats = Inputs.toggle({
label: "Highlight Median & Range",
value: false,
disabled: chartType === "Bar Chart"
})// Bar Chart
barChart = Plot.plot({
width: 600,
height: 400,
marginBottom: 50,
x: {
label: "Group"
},
y: {
label: "Mean Pet Relinquishment Rate (%)",
domain: [0, 50]
},
color: showColor ? {
domain: ["Control", "Intervention"],
range: ["#e15759", "#4e79a7"]
} : undefined,
marks: [
Plot.barY(summary, {
x: "group",
y: "mean",
fill: showColor ? "group" : "#999"
}),
showSD ? Plot.ruleY(summary, {
x: "group",
y1: d => d.mean - d.sd,
y2: d => d.mean + d.sd,
stroke: "black",
strokeWidth: 2
}) : null,
showSD ? Plot.tickX(summary, {
x: "group",
y: d => d.mean - d.sd,
stroke: "black",
strokeWidth: 2
}) : null,
showSD ? Plot.tickX(summary, {
x: "group",
y: d => d.mean + d.sd,
stroke: "black",
strokeWidth: 2
}) : null,
Plot.ruleY([0])
]
})// Boxplot
boxplot = Plot.plot({
width: 600,
height: 400,
marginBottom: 50,
x: {
label: "Group"
},
y: {
label: "Pet Relinquishment Rate (%)",
domain: [0, 60]
},
color: showColor ? {
domain: ["Control", "Intervention"],
range: ["#e15759", "#4e79a7"]
} : undefined,
marks: [
Plot.boxY(data, {
x: "group",
y: "rate",
fill: showColor ? "group" : "#999",
stroke: showColor ? "group" : "#666"
}),
showStats ? Plot.dot(summary, {
x: "group",
y: "median",
r: 5,
fill: "white",
stroke: "black",
strokeWidth: 2
}) : null,
showStats ? Plot.ruleY(summary, {
x: "group",
y: "min",
stroke: "darkred",
strokeWidth: 2,
strokeDasharray: "4,2"
}) : null,
showStats ? Plot.ruleY(summary, {
x: "group",
y: "max",
stroke: "darkred",
strokeWidth: 2,
strokeDasharray: "4,2"
}) : null,
Plot.ruleY([0])
]
})