Dual-axis plot breaks with multiple variables on right/secondary y-axis

I’m facing a garbled plot when I do a dual-axis plot with multiple variables on right/secondary y-axis.
Here, I’m trying to do multiple lineplots on top of a barplot.

using Plots
using Plots.PlotMeasures
pyplot()
bar(rand(10), c=:white, right_margin=1cm)
plot!(twinx(), rand(10), label="v1")
plot!(twinx(), rand(10) * 10, label="v2")

image

I see following issues:

  1. Line plots for both “v1” and “v2” are in the same color
  2. Legend of “v1” is not drawn (I presume it’s hidden by “v2” legend)
  3. Ticks on right y-axis are drawn twice, with different y-range

If I swap left/right y-axis (lineplots on left y-axis, barplot on right/secondary y-axis), then I get what I basically expect, but still unusable as barplot hides detail of all lineplots.

using Plots
using Plots.PlotMeasures
pyplot()
plot(rand(10), label="v1", right_margin=1cm)
plot!(rand(10) * 10, label="v2")
bar!(twinx(), rand(10), label="", c=:white)

image

This happens on both GR and PyPlot backend, and also happens on both Plots v1.16.5 and v1.17.0 (latest).

I’m about to submit a bug ticket, but want to check if I’m not doing something stupid - please let me know if this happens in your environment. Also, if there’s any workaround, please let me know!

1 Like

Not sure if this is a bug but with the array syntax it seems to work fine:

using Plots; gr()
using Plots.PlotMeasures
bar(rand(10), c=:white, right_margin=1cm)
plot!(twinx(), [rand(10), rand(10) * 10], label=["v1" "v2"])

Plots_gr_bar_line_multiaxes

1 Like

I am also not sure if it is a bug or not. But I also think it should be improved.

By the way, the problem of bars hiding line plots can be solved by fillalpha=0.

using Plots
using Plots.PlotMeasures
pyplot(fmt = :svg)
plot(rand(10), label="v1", right_margin=1cm)
plot!(rand(10) * 10, label="v2")
bar!(twinx(), rand(10), label="", fillalpha=0)

2 Likes

Every call to twinx() creates a new axis, so you want to re-use the first one:

julia> axis2 = twinx();

julia> plot!(axis2, rand(10), label="v1")

julia> plot!(axis2, rand(10), label="v2")

But to me using the twinx() stuff in Plots always feels like an uphill struggle - usually once my Plots get that complicated I switch to Makie…

6 Likes

Wow, thank you all for solutions/workarounds!

It brought me new understanding of twinx(), that it can be used to create not only 2, but multiple (N>1) additional y-axis by giving different (x-)offset for each twinx()-ed y-axis. Also, while Makie is still foreign to me, it does have many stunning examples - I definitely should check it out.

1 Like

Maybe a little bit divergent from this topic, but is Makie.jl easier to handle than Plots.jl? I am always struggling to use different backends for different intensions.