How to set x-axis positions in StatPlots' violin plot?

I’d like to create a violin plot of a DataFrame and set each “violin” at its linear respective position. For example, this plot:

# some data to play with
n = 10000
f(k) = randn(k)
df2 = DataFrame(hcat(f(n).+1, f(n).-1, 2*f(n), 0.5*f(n)-3, 2*f(n).^2, abs.(f(n))),
    map(num->Symbol(num),[4,10,15,20,22,30]));
# Now plot a violin of each "Set" on the same graph
@df df2 violin(cols(), xticks=(1:ncol(df2), names(df2)))

… has all the “violins” evenly spaced. I’d like to place them according to their numeric column name. I.e., the x-axis would be linear and the first “violin” would be centered above 4, the next would be centered above 10, …, and the last “violin” would be centered above 30.

How can this violin plot be created?

As usual, this is an issue with DataFrame formatting. The names of a DataFrame are Symbols and are not intended to be parsed as numbers.

Instead, your DataFrame should have a long format:

df2 = DataFrame(a = repeat([4,10,15,20,22,30], inner = n), b =  vcat(f(n).+1, f(n).-1, 2*f(n), 0.5*f(n).-3, 2*f(n).^2, abs.(f(n))))
@df df2 violin(:a, :b)

Nice!

Any way for multicolor and (multitrace?) legend as before?

You can specify the colors as a vector of length 6. Or if you want it automatic like in your previous example, use the group keyword: @df df2 violin(:a, :b, group = :a)

1 Like

Super! Thanks!