A violin plot shows the shape of a numeric distribution. Its curved sides bulge where many observations occur and narrow where few occur. Think of it as a smoothed histogram mirrored around a central axis. Unlike a box plot, which marks selected values such as the median and quartiles, the violin shows how observations are spread across the range. section 6.5 section 6.6
Compare salaries by role
Place a violin at each of five data visualization roles: analyst, developer, designer, scientist, and leadership. Salary runs up the vertical axis. A wider part of a violin means more respondents have salaries in that range. Add a marker for the mean and a line spanning the first to third quartiles so readers can compare those values alongside each distribution. section 6.5 section 6.5
Build each shape from the data:
- For each role, filter the responses and map them to an array of salaries. Calculate its mean with d3.mean(), group its salaries with d3.bin(), and obtain quartiles with d3.scaleQuantile(). section 6.5
- Use a point scale to position roles horizontally and a linear scale to position salaries vertically. Use another linear scale to turn each bin’s observation count into the violin’s half-width. section 6.5
- Draw the bins as histogram bars first to check the shape. Then use d3.area() to trace the bin tips: set its left and right edges to equal distances from the role’s center, and apply d3.curveCatmullRom for curved sides. section 6.5 section 6.5
Listing 6.14 Drawing complete violin plots (violins.js)
roles.forEach(role => {
...
const areaGenerator = d3.area()
.x0(d => xScale(role.id) - violinsScale(d.length)) #1
.x1(d => xScale(role.id) + violinsScale(d.length))
.y(d => yScale(d.x1) + ((yScale(d.x0) - yScale(d.x1))/2))
.curve(d3.curveCatmullRom);
roleContainer
.append("path")
.attr("d", areaGenerator(role.bins))
.attr("fill", slateGray) #2
.attr("fill-opacity", 0.3);
};
The complete area generator maps each bin count to matching left and right widths around a role’s center; the resulting SVG path forms the violin. section 6.5
A violin makes the whole distribution visible, but its width depends on the chosen bins and their counts. Keep the mean and quartile markers when those exact summaries matter to the comparison. section 6.5 section 6.6


