How to use secondary axis for specific series in a groupedbar plot?

Is it possible to specify a secondary y-axis for some of the series in a groupedbar plot ? (I am using Plots.jl/StatsPlots.jl)

I have tried to split it in two separate calls with twinxs(), but it doesn’t work:

x = [1 3 120 270; 3 4 280 240; 2 5 220 270; 4 4 380 320]
groupedbar(x[:,[1,2]])
groupedbar!(twinx(),x[:,[3,4]]) # MethodError: no method matching grouped_xy(::Plots.Subplot{Plots.GRBackend}, ::Matrix{Int64})

Would a result like this be OK:

Thank you, but in your plot the two groups of series have different domain, while in my case the domain (the rows in the table, that is the value in the x axis) would be the same across all the series, just some series have much higher values…

Ah, OK. The same domain case is less complicated. Check if this is alright:

StatsPlots groupedbar secondary y-axis
using StatsPlots; gr(dpi=600)

x = [1 3 120 270.; 3 4 280 240; 2 5 220 270; 4 4 380 320.]

ix1, ix2 = [1,2], [3,4]
x1, x2 = x[:, ix1], x[:, ix2]
scaler = 4 * maximum(x1) / maximum(x2)        # adjust as esthetically desired
xx = copy(x)
xx[:, ix2] .*= scaler
labels = string.(2012:4:2024)
p3 = groupedbar(xx, labels=true, ylabel="Series 1 & 2", xticks=(1:size(x,1), labels), foreground_color_legend=nothing)
plot!(twinx(),  ylims=ylims(p3)./scaler, ylabel="Series 3 & 4")
1 Like

ok, now give me the code :wink:
Makie?

I have posted the Plots.jl / StatsPlots.jl code below the plot.

It quickly illustrates how to do it for your specific example, but the scaling logic should need some more work.

1 Like

Ok, so the trick is to plot all the 4 series, with the 3rd and 4th ones “prescaled” on the y1 axis but then add an opportunity scaled and labeled secondary y axis with not actual series…
Actually this approach could be useful in many cases, as twinx() often gives me problems…
I could manualy prescale the series that should go on the secondary y axis and then just add the empty axis…
Thank you…

1 Like