pythonplotvega-litealtair

Reduce jitter width In vega Altair


I am trying to get into Vega-altair for plotting in python and it seems like a great option. I often have to generate Bar plots with points where the bar shows the mean and the points the single values. To make points with the same value visible I want to jitter them slightly. This works in principle but the jitter is too strong and makes differentiating between groups difficult. Here is my example code to replicate the error

data = pd.DataFrame({
    'group':['A']*5+['B']*5,
    'value':random.sample(range(0,100),10)})
bar = alt.Chart(data).mark_bar().encode(
    x='group',
    y='mean(value)')
point = alt.Chart(data,).mark_circle(color='black').encode(
    x='group',
    xOffset='jitter:Q',
    y='value').transform_calculate(
    jitter='random()')

bar+point

Which yields a plot like this

Barplot with points and too much jitter

I've tried just multiplying the random() function with a small number but this doesn't change anything. Further, adding the xOffset to the points seems to mess with Barplot. When I increase the witdth of the plot the bars remain small and not centered. What am I doing wrong and is there a way to reduce the jitter of the points?

Thanks in advance


Solution

  • By default xOffset gets a domain appropriate for its data, which is [0, 1], and this domains spans the allotted space (as any automatically chosen domain will). You can customize this domain, though, with xOffset=alt.XOffset("jitter:Q", scale=alt.Scale(domain=[-1, 2])). This will confine the results of random() to the middle third of this domain. In general, to confine the jitter to the middle p of the domain (with 0 < p < 1), you'd want the domain to be [(p-1)/(2p), (p+1)/(2p)].