With Makie, how to incrementally add stacked bars to plot?

305 views Asked by At

With the following code, the bars overlap. How to get the bars to stack on top of each other?

using CairoMakie
x = 1:10

b = barplot(x,rand(10))
barplot!(x,rand(10))
b

The result of the above code: A bar plot with overlapping bars instead of stacked bars

1

There are 1 answers

0
AKdemy On

You can do the following based on discourse.julialang.

rnd1 = rand(10)
rnd2 = rand(10)
x = 1:10

fig = Figure();
ax = Axis(fig[1,1]);
barplot!(ax, x, rnd1 .+ rnd2, color=:blue)
barplot!(ax, x, rnd1, color=:orange)
fig

enter image description here

It is a workaround that simply adds both random values together in the first barplot, and puts the second on top.

stack does not work with rand directly (Makie restricts inputs of stack and dodge to integers) but for integers you can use the following code snippet from the documentation:

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]
       )

barplot(tbl.x, tbl.height,
        stack = tbl.grp,
        color = tbl.grp,
        axis = (xticks = (1:3, ["left", "middle", "right"]),
                title = "Stacked bars"),
        )

Of course, if it does not have to be Makie, you can also use something like:

using DataFrames, StatsPlots
groupedbar(hcat(rnd1, rnd2), bar_position=:stack)

enter image description here