I've been trying to get paired distribution (aka "violin") plots like those shown below for a few hours, but all my attempts have failed.
The key features here are
- paired smooth histograms/distribution plots with a common vertical abscissa and divergent horizontal ordinates;
- different fill colors for the two subplots;
The closest Mathematica has are DistributionChart
s, but these plots are not paired (i.e. they are always symmetrical).
I first tried SmoothHistogram
, but it appears that there's no simple way to get a SmoothHistogram
with a vertical abscissa.
Next I tried PairedSmoothHistogram
, but I can't manage to assign different fill colors to the two sides.
BlockRandom[SeedRandom[0];
Quiet[
PairedSmoothHistogram[
RandomVariate[NormalDistribution[], 100]
, RandomVariate[NormalDistribution[], 100]
, AspectRatio -> Automatic
, Axes -> {False, True}
, Ticks -> None
, Spacings -> 0
, ImageSize -> 30
, Filling -> Axis
]
, OptionValue::nodef
]
]
Then I tried a combination of SmoothKernelDistribution
and either ListPlot
, ParametricPlot
or ContourPlot
, but this won't work because neither ParametricPlot
nor ContourPlot
accepts a Fill
option, and I can't figure out how to get ListPlot
to fill the spaces between the curves and the vertical axis.
For example,
violin[data1_, data2_, rest___] := Module[
{ d1 = SmoothKernelDistribution[data1]
, d2 = SmoothKernelDistribution[data2]
, x
, xrange
}, xrange = {x, Sequence @@ (#[data1, data2] & /@ {Min, Max})}
; ParametricPlot[ {{-PDF[d1, x], x}, {PDF[d2, x], x}}
, Evaluate@xrange
, rest
, PlotRange -> All
, Axes -> {None, True}
, Ticks -> None
, PlotRangePadding -> {Automatic, None}
]
];
BlockRandom[SeedRandom[0];
violin[RandomVariate[NormalDistribution[], 100],
RandomVariate[NormalDistribution[], 100],
ImageSize -> 30
]
]
I didn't expect this would be so hard. My brain is now fried.
Does anyone know how one does this?