TomR
TomR

Reputation: 165

Multiple axes in Julia Plots (GR backend)

How do I plot a set of curves with Julia (1.4.1) and Plots in a Jupyter notebook, some of them using the x axis and the left y axis, and some (more than one!) using the x axis and the right y axis? Whatever I try, I always get only one plot (the first one, which gets the twinx command) to use the right y axis, whereas the ones following it use the first (left) axis again. Among several other things, I tried

epl=plot(title="A title",legend=:topright)
epl=plot!(x_arr,y1_arr)
epl=plot!(x_arr,y2_arr)
epl=plot!(twinx(),x_arr,y3_arr,legend=:bottomright)
epl=plot!(x_arr,y4_arr)
display((epl))

and also

epl=plot(title="A title",legend=:topright)
epl=plot!(x_arr,[y1_arr,y2_arr])
epl=plot!(twinx(),x_arr,[y3_arr,y4_arr],legend=:bottomright)
display((epl))

The latter works a bit better, but I don't know how to define individual linestyles, legend labels etc. for each vector element; my attempt to assign matching vectors to the corresponding keyword arguments failed. The label for the second y axis (not included in the example above) does not show up either. The legend is wrong in the first case and does not show up at all in the second case. The interface I use is apparently gr(), which I tend to prefer, but I'm not sure.

Upvotes: 0

Views: 2240

Answers (1)

mbauman
mbauman

Reputation: 31342

The plot! function takes an optional first plot object to modify. If you don't pass in a plot to be modified, it uses the global one.

When you call twinx(), it creates a new subplot that you can plot! into — one that's inside your current global plot — and then it updates and returns the overall plot. Your next plot! just updates the first subplot as usual.

The key is to save your twinned subplot and explicitly plot! into it.

epl=plot(title="A title", legend=:topright)
plot!(x_arr, y1_arr) # could be explicitly `plot!(epl, x_arr, y1_arr)`
plot!(x_arr, y2_arr)
subplot = twinx()
plot!(subplot, x_arr, y3_arr, legend=:bottomright)
plot!(subplot, x_arr, y4_arr)

Upvotes: 2

Related Questions