Reputation: 111
In Julia, using Plots
, I want to plot two series using two different y-axes and one x-axis (using twinx()
) and one legend centered below.
The issue is that adding the legend shifts one of the y-axes and not the other, breaking them apart. How can I add the legend below the plots without breaking them up?
I have figured out how to create a shared legend (also not straightforward in Plots
) by plotting a ghost series outside the limits of the first series to add it to the legend.
MWE:
using Plots
x = -2π:0.01:2π
y1 = sin.(x)
y2 = 2.0 .+ cos.(x)
p =
plot( x, y1, color=:blue)
plot!( x, y2, color=:red, ylims=(-1.0, 1.0))
axis2 = twinx()
plot!(axis2, x, y2, color=:red, label="")
plot!(legend=:outerbottom)
Upvotes: 0
Views: 163
Reputation: 111
It took me forever to figure this out (which is why I ended up posting the question to answer it. Hopefully someone else can find this useful.) I would appreciate a more elegant solution, so I am looking forward to seeing other approaches.
I added a bottom margin to both plots (shifting them up appropriately) and then manually placed the legend using relative coordinates, which does not break apart the y-axes from the x-axis.
Solution:
using Plots, Plots.PlotMeasures
x = -2π:0.01:2π
y1 = sin.(x)
y2 = 2.0 .+ cos.(x)
p =
plot( x, y1, color=:blue)
plot!( x, y2.+0.1, color=:red, ylims=(-1.0, 1.0))
axis2 = twinx()
plot!(axis2, x, y2, color=:red, label="")
plot!(bottom_margin=20mm)
plot!(legend=(0.54, -0.2))
Upvotes: 1