import pandas as pdimport numpy as npimport pandas.api.types as pdtypesfrom plotnine import ( ggplot, aes, stage, geom_violin, geom_point, geom_line, geom_boxplot, guides, scale_fill_manual, theme, theme_classic,)
Violins, Boxes, Points & Lines
Comparing repeated measurements and their summaries
Suppose you have two sets of related data and each point in the first set maps onto a point in the second set. e.g. they could represent a transition from one state to another for example two measurements of the height of pupils in different years.
For demonstration we shall generate data with a before measurement and an after measurement.
The violins are symmetrical about the vertical axis and half a violin has the same information as the full violin. We cut (style) the violins in half and choose to alternate with the left half for the first one and the right half for the second.
Make gap between the points and the violions. i.e. shift the violins outward and the points & lines inward. We used stage mapping to get it done. For example
says, map the xaesthetic to the ‘when’ column/variable and after the scale computed the x locations add a shift to them. The calculated x locations of a discrete scale are consecutive numbers 1, 2, 3, ..., so we use that move objects of adjacent groups in opposite directions i.e $(-1)^1, (-1)^2, (-1)^3 … = -1, 1, -1… $
# How much to shift the violin, points and lines# 0.1 is 10% of the allocated space for the categoryshift =0.1def alt_sign(x):"Alternate +1/-1 if x is even/odd"return (-1) ** xm1 = aes(x=stage("when", after_scale="x+shift*alt_sign(x)")) # shift outwardm2 = aes(x=stage("when", after_scale="x-shift*alt_sign(x)"), group="id") # shift inward( ggplot(df, aes("when", "value"))+ geom_violin(m1, style="left-right") # changed+ geom_point(m2) # changed+ geom_line(m2) # changed)
Add a boxplot in the gap. The space between the flat edge of the violin and the center of the points is 2 * shift, so we can use the shift to control the width of the boxplot.