hline/vline with subplots in Julia

Viewed 1186

I'm trying to add a horizontal line to a subplot, and from this discussion: https://discourse.julialang.org/t/vline-with-subplots/25479/2, I have the following

x = [1,2,3]
y1 = 2x
y2 = x.^2
plot([x, x], [y1, y2], layout = (2, 1))
hline!([4 4])

Which produces the plots.

plots

Now what I'm trying to do is do the horizontal line on the bottom plot, but not the top one. If I just specify hline!([4]) , it defaults to the top one. Is there a way to do the bottom one only?

2 Answers

The trick is to keep track of the plot handles.

p = plot([x, x], [y1, y2], layout = (2, 1))

returns a plot handle (specifically, a Plots.Plot{Plots.GRBackend} object) p with two elements, p[1] (the first subplot) and p[2] (the second subplot). To add the hline to the bottom plot only, then, you can write:

x = [1,2,3]
y1 = 2x
y2 = x.^2
p = plot([x, x], [y1, y2], layout = (2, 1))
hline!(p[2], [4])

enter image description here

It's probably best practice to plot subplots separately (as mentioned on Slack by isentropic):

x = [1,2,3]
y1 = 2x
y2 = x.^2
p1 = plot(x, y1)
p2 = plot(x, y2)
hline!(p2, [4])
plot(p1, p2, layout = (2, 1))

But if you want it all in one go, you could have used

hline!([[NaN], [4]])
Related