Double y-axes in a sub-plot

I would like to have dual y-axes in one of my subplots; however, it seems like I am missing something about twinx() and link = :x, but I couldn’t figure out what…

Plotting double y-axis using twinx() works fine in a standard plotting frame. However, it creates the following problem when I try to link the x-axes. What am I missing here?

using Plots

x = [3, 5, 7, 9];
y = [10, 20, 30 , 40];
z = [-10, -20, -30, -40];

a = plot(1:10, color = :black, legend = false)

b = plot(x, y, color = :green, legend = false)
b = scatter!(twinx(), x, z, color = :orange, legend = false)

plot(a, b, layout = (2, 1), link= :x)

Output:
fig

Thanks very much!

This fixes two issues (small margins and x-ticks labels scrambled):

using Plots, Measures

x = [3, 5, 7, 9];
y = [10, 20, 30 , 40];
z = [-10, -20, -30, -40];

a = plot(1:10, color = :black, legend = false)

b = plot(x, y, color=:green, legend=false, margin=10mm)
scatter!(twinx(), x, z, color=:orange, legend=false, xlims=xlims(a))

plot(a, b, layout = (2, 1), link=:x, tickfontcolor=:black)

2 Likes

I am extremely grateful! Thanks very much for your time!

1 Like