MakieOrg / Makie.jl

Interactive data visualizations and plotting in Julia
https://docs.makie.org/stable
MIT License
2.37k stars 302 forks source link

Errorbars for grouped barplots #3300

Open gschivre opened 10 months ago

gschivre commented 10 months ago

Feature description

Adding errorbars over grouped barplots is surprinsgly difficult in Makie, although it's a very common feature for statistical ploting library (see this post on julia discourse). I found a workaround:

using CairoMakie
tbl = (x = [1, 1, 1, 2, 2, 2, 3, 3, 3],
              height = 0.1:0.1:0.9,
              grp = [1, 2, 3, 1, 2, 3, 1, 2, 3],
              grp1 = [1, 2, 2, 1, 1, 2, 1, 1, 2],
              grp2 = [1, 1, 2, 1, 2, 1, 1, 2, 1],
              err = 0.1 * (0.1:0.1:0.9)
              )

dodge_gap = 0.03 #Makie default
gap = 0.2 #Makie default
width = 1 #Makie default
function compute_x(x, width, gap, dodge, dodge_gap)
    scale_width(dodge_gap, n_dodge) = (1 - (n_dodge - 1) * dodge_gap) / n_dodge
    function shift_dodge(i, dodge_width, dodge_gap)
        (dodge_width - 1) / 2 + (i - 1) * (dodge_width + dodge_gap)
    end
    width *= 1 - gap
    n_dodge = maximum(dodge)
    dodge_width = scale_width(dodge_gap, n_dodge)
    shifts = shift_dodge.(dodge, dodge_width, dodge_gap)
    return x .+ width .* shifts
end
xerr = compute_x(tbl.x, width, gap, tbl.grp, dodge_gap)

fig, ax, plt = barplot(tbl.x, tbl.height;
               dodge = tbl.grp,
               color = tbl.grp,
               axis = (xticks = (1:3, ["left", "middle", "right"]),
                       title = "Stacked bars"), dodge_gap = dodge_gap, gap = gap, width = width)
errorbars!(ax, xerr,
                tbl.height, tbl.err; whiskerwidth = 10)
display(fig)

This work fine but might be a bit involved for end users. Adding a dodge option to errorbars looks straightforward however it should include a dodge_gap, gap and width arguments which refers to the argument of the "parent" barplot which might get confusing (or may be renaming them parent_dodge_gap, parent_gapand parent_width would enough ?).

For plot types, please add an image of how it should look like

dodged_barplot_with_error

pdeffebach commented 4 months ago

Bumping this! I've been trying to figure out how to do this today. I wish it were easier.